swagger 是一个主流的API开发框架,可以自动生成在线访问web项目的接口列表。 项目集成swagger,可以显著提升调试接口的效率。官网地址 swagger.io/
本文主要介绍spring boot配置swagger的最佳实践。
最佳实践
1 配置依赖
dependencies {
compile "org.springframework.boot:spring-boot-starter-web:2.6.1",
compile 'io.springfox:springfox-boot-starter:3.0.0'
}
2. 创建swagger配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket documentation() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.demo"))
.build()
.pathMapping("/")
.apiInfo(apiInfo())
.enable(true);
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("API document")
.description("Demo api")
.version("1.0")
.build();
}
3. 在application.properties配置文件中设置如下
spring.mvc.pathmatch.matching-strategy=ant-path-matcher
注意:spring boot 2.6.0以下版本不用配置。 springboot 2.6.0及以上版本由于依赖的Spring MVC 处理映射匹配的默认策略已从AntPathMatcher更改为PathPatternParser。如果不换为AntPathMatcher,应用启动时将报如下错误:
[ERROR][main][2021-12-16 21:29:30 030][20280][SpringApplication.java:819][][]Application run failed
org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:181) ~[spring-context-5.3.13.jar:5.3.13]
at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:54) ~[spring-context-5.3.13.jar:5.3.13]
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356) ~[spring-context-5.3.13.jar:5.3.13]
at java.lang.Iterable.forEach(Iterable.java:75) ~[?:1.8.0_192]
3 访问swagger api页面
http://localhost:8080/swagger-ui/index.html
4 安全问题
生产环境是不允许打开swagger页面的,可以配置在生产环境禁用swagger,开发和测试环境打开swagger。 在prod配置中设置:
springfox.documentation.enabled=false
禁用swagger页面。
在dev和test配置中设置
springfox.documentation.enabled=true
开启swagger页面。
不推荐方式
不推荐理由:
- 不支持最新swagger版本,容易出现路径404错误
- 最佳实践方式swagger界面更友好使用。
1 配置依赖
dependencies {
compile "org.springframework.boot:spring-boot-starter-web:2.6.1",
compile 'io.springfox:springfox-swagger2:2.9.2'
compile 'io.springfox:springfox-swagger-ui:2.9.2'
}
springfox-xxx需要设置在2.9.2及以下版本(使用最新3.0.0版本报404错误,2.10.0 ~2.10.5配置类报错)。当spring boot使用2.6.0以上,同样需要另外配置
spring.mvc.pathmatch.matching-strategy=ant-path-matcher
2 创建swagger配置类
该步与与最佳实践相同。
3 访问swagger api页面
http://localhost:8080/swagger-ui.html
另外,两种配置方式访问路径不同,如果用混了,也将赠送一个404错误页面。两种配置方式都不需要在项目中放置swagger前端静态资源文件,除非有前端定制化需求。