Springboot2.7整合Swagger3 Springboot2.7.x改动较大,Swagger3.0.0也是改动较大,两个一掺和,一堆问题就出来了。
引入依赖 1 2 3 4 5 6 7 8 9 10 <dependency > <groupId > io.springfox</groupId > <artifactId > springfox-swagger2</artifactId > <version > 3.0.0</version > </dependency > <dependency > <groupId > io.springfox</groupId > <artifactId > springfox-boot-starter</artifactId > <version > 3.0.0</version > </dependency >
原先的springfox-swagger-ui依赖似乎不需要了。 2.10.x版本中的@EnableSwagger2注解被移除了,3.0.0又添加回来了,但是我这边@EnableSwagger2注解不起作用,还是换成springfox-boot-starter依赖吧。 参考链接:Replace @EnableSwagger2 after update to latest version - stackoverflow
添加配置 在项目中新建 SwaggerConfig 配置文件
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 package com.subaru.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import springfox.documentation.builders.ApiInfoBuilder;import springfox.documentation.builders.PathSelectors;import springfox.documentation.builders.RequestHandlerSelectors;import springfox.documentation.service.ApiInfo;import springfox.documentation.spi.DocumentationType;import springfox.documentation.spring.web.plugins.Docket;@Configuration public class SwaggerConfig { @Bean public Docket docket () { return new Docket (DocumentationType.OAS_30) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo () { return new ApiInfoBuilder ().build(); } }
原先的@EnableSwagger2注解我换成了springfox-boot-starter依赖。
修改yml 1 2 3 4 spring: mvc: pathmatch: matching-strategy: ant_path_matcher
Springfox 假设 Spring MVC 的路径匹配策略是 ant-path-matcher,而 Spring Boot 2.6.x及以后版本的默认匹配策略是 path-pattern-matcher,不修改会造成下方documentationPluginsBootstrapper报错。
1 org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException...
参考链接:Spring Boot 2.6.x整合Swagger启动失败报错问题解决(治标还治本) - csdn
编写测试类 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 package com.subaru.controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RestController;@RestController public class HelloController { @GetMapping("/hello") public String hello () { return "Get Hello" ; } @PostMapping("/world") public String world () { return "Post World" ; } }
启动访问 访问 http://localhost:8080/swagger-ui/index.html 即可看到新版swagger界面,至此整合结束。