• Springboot2.x整合Swagger3.x


    1、SpringBoot添加pom文件依赖

        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.4.11</version>
            <relativePath/>
        </parent>
    
        <properties>
            <java.version>11</java.version>
        </properties>
    
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-web</artifactId>
            </dependency>
            <!--swagger3依赖-->
            <dependency>
                <groupId>io.springfox</groupId>
                <artifactId>springfox-boot-starter</artifactId>
                <version>3.0.0</version>
            </dependency>
    
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.16</version>
                <scope>provided</scope>
            </dependency>
    
        </dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-maven-plugin</artifactId>
                </plugin>
            </plugins>
        </build>

    2、配置文件增加配置

    server:
      port: 8082
    
    spring:
      application:
        name: swagger-server
    
    swagger:
      enable: true
      application-name: ${spring.application.name}
      application-version: 1.0
      application-description: 电商平台管理后端接口文档

    3、创建配置类

    import io.swagger.annotations.ApiOperation;
    import lombok.Data;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.context.annotation.Bean;
    import org.springframework.stereotype.Component;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.oas.annotations.EnableOpenApi;
    import springfox.documentation.service.*;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spi.service.contexts.SecurityContext;
    import springfox.documentation.spring.web.plugins.Docket;
    
    import java.util.ArrayList;
    import java.util.Collections;
    import java.util.List;
    
    /**
     * @author baot
     * @title Swagger3 插件配置
     * @description
     * @date 2021-10-14
     * @update
     * @className SwaggerConfiguration
     */
    @Component
    @EnableOpenApi
    @ConfigurationProperties("swagger")
    @Data
    public class SwaggerConfiguration {
        /**
         * 是否开启swagger,生产环境一般关闭,所以这里定义一个变量
         */
        private Boolean enable;
    
        /**
         * 项目应用名
         */
        private String applicationName;
    
        /**
         * 项目版本信息
         */
        private String applicationVersion;
    
        /**
         * 项目描述信息
         */
        private String applicationDescription;
    
        @Bean
        public Docket docket() {
            return new Docket(DocumentationType.OAS_30)
                    .pathMapping("/")
                    // 定义是否开启swagger,false为关闭,可以通过变量控制,线上关闭
                    .enable(enable)
                    .select()
                    .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                    .paths(PathSelectors.any()).build()
                    // 如何保护我们的Api,有三种验证(ApiKey, BasicAuth, OAuth)
                    .securitySchemes(security())
                    //全局控制token
                    .securityContexts(Collections.singletonList(SecurityContext.builder().securityReferences(Collections.singletonList(SecurityReference.builder().scopes(new AuthorizationScope[0]).reference("token").build()))
                     // 声明作用域
                     .operationSelector(o -> o.requestMappingPattern().matches("/.*"))
                     .build()))
                    // 接口文档的基本信息
                    .apiInfo(apiInfo());
        }
    
    
        /**
         * 接口文档详细信息
         *
         * @return
         */
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title(applicationName)
                    .description(applicationDescription)
                    //.contact(new Contact("联系标题", "https://www.baidu.com", "510716143@qq.com"))
                    .version(applicationVersion)
                    .build();
        }
    
        private List<SecurityScheme> security() {
            ArrayList<SecurityScheme> apiKeys = new ArrayList<>();
            apiKeys.add(new ApiKey("token", "token", "header"));
            return apiKeys;
        }
        
    }

    4、创建controller类

    import com.example.model.User;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiImplicitParam;
    import io.swagger.annotations.ApiImplicitParams;
    import io.swagger.annotations.ApiOperation;
    import io.swagger.v3.oas.annotations.responses.ApiResponse;
    import io.swagger.v3.oas.annotations.responses.ApiResponses;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.ArrayList;
    import java.util.List;
    
    @Api(tags = "测试接口")
    @RestController
    @RequestMapping("demo")
    public class DemoController {
    
        @ApiOperation("查询集合数据")
        @ApiImplicitParams(value = {
                @ApiImplicitParam(name = "id",value = "查询id"),
                @ApiImplicitParam(name = "name",value = "查询名称",required = true)
        })
        @ApiResponses({
                @ApiResponse(responseCode = "200", description ="OK"),
                @ApiResponse(responseCode = "204", description ="No results returned")
        })
        @PostMapping("list1")
        public List<String> list1(Integer id,String name){
            List<String> list = new ArrayList<>();
            list.add("张三");
            list.add("李四");
            return list;
        }
    
        @ApiOperation("测试删除")
        @ApiImplicitParam(name = "id", value = "删除ID", example = "100", required = true)
        @PostMapping(value = "/delete/{id}")
        public Integer delete(@PathVariable("id") Long id){
            System.out.println("删除成功:"+id);
            return 200;
        }
    
        @ApiOperation("保持对象")
        @PostMapping("save")
        public Object save(@RequestBody User user){
            User user1 = new User();
            user1.setId(user.getId());
            user1.setName(user.getName());
            return user1;
        }
    
    }

    5、访问 http://localhost:8082/swagger-ui/index.html

    6、常用注解,官网

    @Api()用于类;
    表示标识这个类是swagger的资源


    @ApiOperation()用于方法;
    表示一个http请求的操作


    @ApiParam()用于方法,参数,字段说明;
    表示对参数的添加元数据(说明或是否必填等)


    @ApiModel()用于类
    表示对类进行说明,用于参数用实体类接收


    @ApiModelProperty()用于方法,字段
    表示对model属性的说明或者数据操作更改


    @ApiIgnore()用于类,方法,方法参数
    表示这个方法或者类被忽略


    @ApiImplicitParam() 用于方法
    表示单独的请求参数


    @ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam

    具体使用举例说明:


    @Api()
    用于类;表示标识这个类是swagger的资源
    tags–表示说明
    value–也是说明,可以使用tags替代

  • 相关阅读:
    在 electron-vue 中的 Windows 下的路径问题,path.resolve 替换为 path.posix.join 。
    NLTK数据包下载频繁报错——解决方法
    常用正则表达式匹配
    NLTK的安装与简单测试
    Scrapy模块使用出错,出现builtins.ImportError: DLL load failed: 找不到指定的程序
    正则表达式手册
    数据分布vs聚类-数据预处理技巧-对数变换
    Python机器学习入门(1)之导学+无监督学习
    Pygame游戏开发入门(1)-开发框架
    Python-文件和数据格式化
  • 原文地址:https://www.cnblogs.com/M87-A/p/15363834.html
Copyright © 2020-2023  润新知