Springboot2.7整合Swagger3
Springboot2.7.x改动较大,Swagger3.0.0也是改动较大,两个一掺和,一堆问题就出来了。
1.引入依赖
<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
2.添加配置
在项目中新建 SwaggerConfig 配置文件
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
依赖。
3.修改yml
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
Springfox 假设 Spring MVC 的路径匹配策略是 ant-path-matcher,而 Spring Boot 2.6.x及以后版本的默认匹配策略是 path-pattern-matcher,不修改会造成下方documentationPluginsBootstrapper
报错。
org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException...
参考链接:Spring Boot 2.6.x整合Swagger启动失败报错问题解决(治标还治本) - csdn
4.编写测试类
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";
}
}
5.启动访问
访问http://localhost:8080/swagger-ui/index.html即可看到新版swagger界面,至此整合结束。