一、SpringBoot整合Swagger

前后端分离的SpringBoot+SpringSecurity+Swagger项目,主要示范Swagger的使用方法

1、添加Swagger依赖

注意如果SpringBoot是2.6版本的话可能会报错,处理过程在结尾

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.7.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.7.0</version>
</dependency>

2、编写Swagger配置类

在SpringBoot启动类的同级目录下创建一个包config,然后在config包下编写Swagger配置类

@Configuration
@EnableSwagger2   //开启swagger
public class SwaggerConfig {

    @Bean
    public Docket createRestApi(Environment environment) {

        return new Docket(DocumentationType.SWAGGER_2)
                //apiInfo指定测试文档基本信息,这部分将在页面展示
                .apiInfo(apiInfo())
                .select()
                //apis() 控制哪些接口暴露给swagger,
                // RequestHandlerSelectors.any() 所有都暴露
                // RequestHandlerSelectors.basePackage("com.info.*")  指定包位置
                .apis(RequestHandlerSelectors.basePackage("com.guet.controller"))
                // 扫码该包下的所有路径
                .paths(PathSelectors.any())
                .build();
    }

    //基本信息,页面展示
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("图片分享软件")
                .description("API接口")
                //联系人实体类
                .contact(
            			//三个参数分别是 联系人姓名、联系人网站、邮箱
                        new Contact("LZDWTL", "https://www.baidu.com/", "1020202@qq.com")
                )
                //版本号
                .version("1.0")
                .build();
    }
}

3、在控制层添加Swagger注释

@RestController
//Api注解,描述信息 可通过tag进行分类
@Api(value = "LoginController")
public class LoginController {

    @Autowired
    private LoginService loginService;

    @PostMapping("/doLogin")
    //方法描述
    @ApiOperation(notes = "登陆", value = "doLogin")
    public RespBean doLogin(@ApiParam(name = "LoginDTO", value = "用户登陆信息") @RequestBody LoginDTO loginDTO){
        //传输参数的描述
        return loginService.doLogin(loginDTO);
    }

    @PostMapping("/doLogout")
    @ApiOperation(notes = "登出", value = "doLogout")
    public RespBean doLogout(){
        return loginService.doLogout();
    }
}

如果只是SpringBoot+Swagger的话,写完第三步已经可以进行测试了。测试网址如下

http://localhost:8080/swagger-ui.html

但是如果还整合了SpringSecurity的话,那还需要再进行第四步。

4、对静态资源放行

在SpringSecurity配置类中允许静态资源被访问,重写configure()方法即可

完成第四步就全部完成了

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    public void configure(WebSecurity web) {
        //swagger2所需要用到的静态资源,允许访问
        web.ignoring().antMatchers("/v2/api-docs",
                "/swagger-resources/configuration/ui",
                "/swagger-resources",
                "/swagger-resources/configuration/security",
                "/swagger-ui.html",
                "/webjars/**");
    }
}

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FovQaHPj-1657609284351)(https://dn-simplecloud.shiyanlou.com/courses/uid1534017-20220214-1644850332234)]

5、切换环境

因为开发环境是内部人员,生产环境是客户,为了程序的安全性,所以在开发环境开启SwaggerUI ,生产环境关闭SwaggerUI 。

1、修改配置类

@Configuration
@EnableSwagger2   //开启swagger
public class SwaggerConfig {

    @Bean
    public Docket createRestApi(Environment environment) {

        /**
         * 在开发环境开启SwaggerUI ,生产环境关闭SwaggerUI 是因为开发环境是内部人员,生产环境是客户。为了程序的安全性需要关闭SwagggerUI
         */
        //设置要显示的Swagger 环境,这里设置只有dev环境才能查看swagger文档
        Profiles profiles =Profiles.of("dev");
        /**
         * 通过 environment.acceptsProfiles 返回的boolean值判断是否处在自己所设定的环境中
         */
        boolean flag = environment.acceptsProfiles(profiles);
        System.out.println(flag);

        return new Docket(DocumentationType.SWAGGER_2)
                //apiInfo指定测试文档基本信息,这部分将在页面展示
                .apiInfo(apiInfo())
                .enable(flag)
                .select()
                //apis() 控制哪些接口暴露给swagger,
                // RequestHandlerSelectors.any() 所有都暴露
                // RequestHandlerSelectors.basePackage("com.info.*")  指定包位置
                .apis(RequestHandlerSelectors.basePackage("com.guet.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    //基本信息,页面展示
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("图片分享软件")
                .description("图片分享软件API文档")
                //联系人实体类
                .contact(
                        new Contact("LZDWTL", "https://www.baidu.com/", "1020202@qq.com")
                )
                //版本号
                .version("1.0")
                .build();
    }
}

2、修改yml文件

添加两个yml文件,命名为 application-dev.yml 和 application-pro.yml

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-2eA1BCfZ-1657609284352)(https://dn-simplecloud.shiyanlou.com/courses/uid1534017-20220215-1644935125467)]

2.1、application.yml

激活dev环境,则可以查看Swagger(这个文件只需要写这三行代码就可以了,不需要配置其他东西)

spring:
  profiles:
    active: dev
2.2、application-dev.yml

dev 和 pro 环境主要是端口号不一样,其他配置内容都一样,都需要设置数据库、redis等东西

server:
  port: 8080
2.3、application-pro.yml
server:
  port: 8081

激活pro环境再访问8081端口则会遭到拒绝

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-rfJnzIgj-1657609284352)(https://dn-simplecloud.shiyanlou.com/courses/uid1534017-20220215-1644935651408)]

6、分组

创建几个Docket,在Docket中给一个名字,然后编写对应的配置就能分组了

@Configuration
@EnableSwagger2   //开启swagger
public class SwaggerConfig {
    
    @Bean
    public Docket docket1() {

        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("A");
    }
    
    @Bean
    public Docket docket2() {

        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("B");
    }

    @Bean
    public Docket createRestApi(Environment environment) {

        return new Docket(DocumentationType.SWAGGER_2)
            	.groupName("LZDWTL")
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.guet.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    //基本信息,页面展示
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("图片分享软件")
                .description("图片分享软件API文档")
                //联系人实体类
                .contact(
                        new Contact("LZDWTL", "https://www.baidu.com/", "1020202@qq.com")
                )
                //版本号
                .version("1.0")
                .build();
    }
}

二、SpringBoot使用Swagger报错

1、错误

org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException

2、原因

这是因为Springfox使用的路径匹配是基于AntPathMatcher的,而Spring Boot 2.6.X使用的是PathPatternMatcher。

3、解决方法

修改application.yaml文件

spring:
  mvc:
    pathmatch:
      matching-strategy: ant_path_matcher
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。