• Springboot集成Swagger2(亲测直接可用)


    1:springboot2.6以下与swagger整合

    1-1:在springboot启动类配置如下,方便启动项目直接看到路径,点击可直接测试

    @Slf4j
    @SpringBootApplication
    public class SpbthymyibatisApplication {
    
        public static void main(String[] args) throws UnknownHostException {
            ConfigurableApplicationContext application =SpringApplication.run(SpbthymyibatisApplication.class, args);
            Environment env = application.getEnvironment();
            String ip = InetAddress.getLocalHost().getHostAddress();
            String port = env.getProperty("server.port");
            String path = env.getProperty("server.servlet.context-path");
            log.info("\n----------------------------------------------------------\n\t" +
                    "Application Jeecg-Boot is running! Access URLs:\n\t" +
                    "Local: \t\thttp://localhost:" + port + path + "/\n\t" +
                    "External: \thttp://" + ip + ":" + port + path + "/\n\t" +
                    "swagger-ui: \thttp://" + ip + ":" + port + path + "/swagger-ui.html\n\t" +
                    "Doc: \t\thttp://" + ip + ":" + port + path + "/doc.html\n" +
                    "----------------------------------------------------------");
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    1-2:Swagger配置类

    package com.example.config;
    
    import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
    import io.swagger.annotations.Api;
    import io.swagger.annotations.ApiOperation;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import springfox.documentation.builders.ApiInfoBuilder;
    import springfox.documentation.builders.ParameterBuilder;
    import springfox.documentation.builders.PathSelectors;
    import springfox.documentation.builders.RequestHandlerSelectors;
    import springfox.documentation.schema.ModelRef;
    import springfox.documentation.service.ApiInfo;
    import springfox.documentation.service.Parameter;
    import springfox.documentation.spi.DocumentationType;
    import springfox.documentation.spring.web.plugins.Docket;
    import springfox.documentation.swagger2.annotations.EnableSwagger2;
    
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * @Author dell
     * @create 2022/11/8
     */
    @Slf4j
    @Configuration
    @EnableSwagger2
    public class SwaggerConfig {
    
        /**
         * swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
         *
         * @return Docket
         */
        @Bean
        public Docket createRestApi() {
            ParameterBuilder tokenPar = new ParameterBuilder();
            List<Parameter> pars = new ArrayList<>();
            tokenPar.name("X-Access-Token").description("AccessToken令牌").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
            pars.add(tokenPar.build());
            return new Docket(DocumentationType.SWAGGER_2)
                    .apiInfo(apiInfo())
                    .select()
                    //扫描方式1,此包路径下的类,才生成接口文档
                    .apis(RequestHandlerSelectors.basePackage("com.example.controller"))
                    //扫描方式2:扫描所有有类注解的api,加了Api注解的类,才生成接口文档
                    .apis(RequestHandlerSelectors.withClassAnnotation(Api.class))
                    //扫描方式3:扫描所有有方法注解的ApiOperation,用这种方式更灵活,才生成接口文档
                    .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                    // 扫描方式4:扫描所有
                    .paths(PathSelectors.any())
                    .build()
                    .globalOperationParameters(pars);
        }
    
        /**
         * api文档的详细信息函数,注意这里的注解引用的是哪个
         *
         * @return
         */
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    .title("Spbthymyibatis 后台服务API接口文档")
                    .description("restful 风格接口")
                    .termsOfServiceUrl("http://www.baidu.com/")
                    .version("1.0")
                    .build();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71

    1-3:在yaml或者properties文件配置

    server.port=8888
    server.servlet.context-path=/spbthymeibatis
    #注意必须要有此行ant匹配,不然swagger启动报错
    spring.mvc.pathmatch.matching-strategy=ANT_PATH_MATCHER
    #扫描实体类
    mybatis.type-aliases-package=com.example.entity
    #扫描映射文件
    mybatis.mapper-locations: classpath:mapper/*.xml
    
    #配置数据库
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=false&autoReconnect=true&failOverReadOnly=false&autoReconnectForPools=true
    spring.datasource.username=root
    spring.datasource.password=root
    
    #过滤静态资源
    spring.mvc.static-path-pattern=/**
    
    #指定系统直接访问路径
    spring.web.resources.static-locations = classpath:/templates/,classpath:/META-INF/resources/,classpath:/resources/
    #热部署:修改后台文件保存后自动重启
    #spring.devtools.restart.enabled=true
    
    #Messages资源信息
    #spring.messages.basename=messages
    
    #关闭thymeleaf缓存 开发时使用 否则没有实时画面
    spring.thymeleaf.cache=false
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29

    1-4:pom配置

    
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
        <modelVersion>4.0.0modelVersion>
        <parent>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-parentartifactId>
            <version>2.6.1version>
            <relativePath/> 
        parent>
        <groupId>com.examplegroupId>
        <artifactId>spbthymyibatisartifactId>
        <version>0.0.1-SNAPSHOTversion>
        <packaging>warpackaging>
    
        <name>spbthymyibatisname>
        <description>Demo project for Spring Bootdescription>
        <properties>
            <java.version>1.8java.version>
        properties>
        <dependencies>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-jdbcartifactId>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-thymeleafartifactId>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-webartifactId>
            dependency>
            <dependency>
                <groupId>org.mybatis.spring.bootgroupId>
                <artifactId>mybatis-spring-boot-starterartifactId>
                <version>2.2.0version>
            dependency>
    
            <dependency>
                <groupId>mysqlgroupId>
                <artifactId>mysql-connector-javaartifactId>
                <scope>runtimescope>
            dependency>
            <dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-testartifactId>
                <scope>testscope>
            dependency>
            
            
            <dependency>
                <groupId>io.swaggergroupId>
                <artifactId>swagger-annotationsartifactId>
                <version>1.5.21version>
            dependency>
            <dependency>
                <groupId>io.swaggergroupId>
                <artifactId>swagger-modelsartifactId>
                <version>1.5.21version>
            dependency>
            
            <dependency>
                <groupId>io.springfoxgroupId>
                <artifactId>springfox-swagger2artifactId>
                <version>2.9.2version>
            dependency>
            <dependency>
                <groupId>io.springfoxgroupId>
                <artifactId>springfox-swagger-uiartifactId>
                <version>2.9.2version>
            dependency>
            <dependency>
                <groupId>com.github.xiaoymingroupId>
                <artifactId>swagger-bootstrap-uiartifactId>
                <version>1.9.3version>
            dependency>
            <dependency>
                <groupId>io.springfoxgroupId>
                <artifactId>springfox-bean-validatorsartifactId>
                <version>2.9.2version>
            dependency>
    
            
            <dependency>
                <groupId>org.projectlombokgroupId>
                <artifactId>lombokartifactId>
            dependency>
    
    
        dependencies>
    
        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.pluginsgroupId>
                    <artifactId>maven-resources-pluginartifactId>
                    <version>3.1.0version>
                plugin>
            plugins>
        build>
    
    project>
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104

    1-5:将接口文档暴露在外网会出现一定的安全问题,此时我们需要给Swagger文档配置登录密码

    1-6:添加依赖,已经添加过

    <dependency>
        <groupId>com.github.xiaoymingroupId>
        <artifactId>swagger-bootstrap-uiartifactId>
        <version>1.9.3version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5

    1-7:更新配置类,再配置类加上@EnableSwaggerBootstrapUI

    @Configuration
    @EnableSwagger2
    @EnableSwaggerBootstrapUI 	//添加注解
    public class SwaggerConfig {
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    1-8:在yaml或者properties文件添加

    # true为启动用密码,false为关闭密码
    swagger.basic.enable=true
    swagger.basic.username=admin
    swagger.basic.password=admin
    
    
    • 1
    • 2
    • 3
    • 4
    • 5

    1-9:Swagger常用注解

    控制类上

    @Api(tags = "控制类")
    
    • 1

    控制类的方法上

    @ApiOperation(value = "方法", notes = "方法")
    
    • 1

    控制类方法参数上使用

    @ApiParam(value = "参数", allowableValues = "range[1,10]", required = true)
    
    • 1
        @ApiOperation(value = "根据id查询")
        @GetMapping(value = {"/findById/{id}"})
        public ItooResult findById(@ApiParam(value = "主键id", required = true) @PathVariable String id) {
            PhoneticEntity phoneticEntity = phoneticService.getById(id);
            return ItooResult.build(ItooResult.SUCCESS, "查询成功", phoneticEntity);
        }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    控制类方法上这是请求的@ApiImplicitParams、@ApiImplicitParam

    @ApiImplicitParams({
    		@ApiImplicitParam(name="phonenum",value="手机号",required=true,paramType="query",dataType="Long"),
    		@ApiImplicitParam(name="password",value="密码",required=true,paramType="query",dataType="String"),
    		@ApiImplicitParam(name="age",value="年龄",required=true,paramType="query",dataType="Integer")
    	})
    
    • 1
    • 2
    • 3
    • 4
    • 5

    控制类方法上这是响应的@ApiResponses、@ApiResponse

    @ApiResponses({
    		@ApiResponse(code = 200, message = "请求成功"),
    		@ApiResponse(code = 400, message = "请求参数没填好"),
    		@ApiResponse(code = 404, message = "请求路径没有或页面跳转路径不对")
    	})
    	
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    实体类,dot,vo,entity上

    @ApiModel(value="对象", description="对象")     
    
    • 1

    实体类,dot,vo,entity的属性上,example 是默认值

    @ApiModelProperty(value = "属性" ,required = true,example = "0")
    
    • 1

    注意:yaml或者properties配置文件里面的空格和缩进都要特别注意,不能有多余,不然识别不出来

    2:springboot2.6以上与swagger整合

    2-1:pom.xml配置

    <parent>
           <groupId>org.springframework.bootgroupId>
           <artifactId>spring-boot-starter-parentartifactId>
           <version>2.6.6version>
           <relativePath/> 
    parent>
    
    <dependency>
        <groupId>com.github.xiaoymingroupId>
        <artifactId>knife4j-spring-boot-starterartifactId>
        <version>3.0.3version>
    dependency>
     
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    2-2:Swagger2Configg配置类

    @Configuration
    @EnableSwagger2    //开启 Swagger2
    @Import(BeanValidatorPluginsConfiguration.class)
    public class Swagger2Config implements WebMvcConfigurer {
    
        /**
         * 显示swagger-ui.html文档展示页,还必须注入swagger资源:
         *
         * @param registry
         */
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
            registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
            registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
            registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
        }
    
        /**
         * swagger2的配置文件,这里可以配置swagger2的一些基本的内容,比如扫描的包等等
         *
         * @return Docket
         */
        @Bean(value = "defaultApi2")
        public Docket defaultApi2() {
            return new Docket(DocumentationType.SWAGGER_2)
                    //.enable(false)
                    .apiInfo(apiInfo())
                    .select()
                    //此包路径下的类,才生成接口文档
                    .apis(RequestHandlerSelectors.basePackage("com.example.poi.controller"))
                    //加了ApiOperation注解的类,才生成接口文档
                    .apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
                    .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                    .paths(PathSelectors.any())
                    .build()
                    .securitySchemes(Collections.singletonList(securityScheme()))
                    .securityContexts(securityContexts())
                    .globalOperationParameters(setHeaderToken());
        }
    
        /***
         * oauth2配置
         * 需要增加swagger授权回调地址
         * http://localhost:8888/webjars/springfox-swagger-ui/o2c.html
         * @return
         */
        @Bean
        SecurityScheme securityScheme() {
            return new ApiKey("X-Access-Token", "X-Access-Token", "header");
        }
    
        /**
         * JWT token
         *
         * @return
         */
        private List<Parameter> setHeaderToken() {
            ParameterBuilder tokenPar = new ParameterBuilder();
            List<Parameter> pars = new ArrayList<>();
            tokenPar.name("X-Access-Token").description("token").modelRef(new ModelRef("string")).parameterType("header").required(false).build();
            pars.add(tokenPar.build());
            return pars;
        }
    
        /**
         * api文档的详细信息函数,注意这里的注解引用的是哪个
         *
         * @return
         */
        private ApiInfo apiInfo() {
            return new ApiInfoBuilder()
                    // //大标题
                    .title("demo 后台服务API接口文档")
                    // 版本号
                    .version("1.0")
                    // 描述
                    .description("后台API接口")
                    // 作者
                    .contact(new Contact("公司", "url", "com"))
                    .license("The Apache License, Version 2.0")
                    .licenseUrl("http://www.apache.org/licenses/LICENSE-2.0.html")
                    .build();
        }
    
        /**
         * 新增 securityContexts 保持登录状态
         */
        private List<SecurityContext> securityContexts() {
            return new ArrayList(
                    Collections.singleton(SecurityContext.builder()
                            .securityReferences(defaultAuth())
                            .forPaths(PathSelectors.regex("^(?!auth).*$"))
                            .build())
            );
        }
    
        private List<SecurityReference> defaultAuth() {
            AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
            AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
            authorizationScopes[0] = authorizationScope;
            return new ArrayList(
                    Collections.singleton(new SecurityReference("X-Access-Token", authorizationScopes)));
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105

    2-3:Springfox 使用的路径匹配是基于AntPathMatcher的,而Spring Boot 2.6版本所使用的是PathPatternMatcher,解决办法如下:在application.yml中加入以下配置

    spring:
      mvc:
        path match:
          matching-strategy: ant_path_matcher
    
    • 1
    • 2
    • 3
    • 4

    2-4:配置swagger账号密码管理,线上不开启,在application.yml中加入以下配置

    #swagger
    knife4j:
      #开启增强配置
      enable: true
      #开启生产环境屏蔽
      production: false
      basic:
        enable: true
        username: admin
        password: 12456
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
  • 相关阅读:
    Swift基础语法 - 可选项
    DirectX12_Windows_GameDevelop_4:Direct3D应用程序框架
    一文详解Redis键过期策略,最全文档
    C# 子类如何访问子类的方法(同一父类)
    嵌入式系统 期末复习提纲
    【软件测试】坚持才有骄傲的资格,8年测试老鸟给我的忠告......
    如何快速教你看自己电脑cpu是几核几线程
    obsidian加git备份,同时忽略掉自己不想同步的文件夹
    typescript: Builder Pattern
    Shunted Self-Attention via Multi-Scale Token Aggregation
  • 原文地址:https://blog.csdn.net/qq_19891197/article/details/127751249