導入依賴
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!--用于訪問http://localhost:8080/swagger-ui.html-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!--用于訪問http://localhost:8080/doc.html-->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.6</version>
</dependency>
<!--因為swagger2 是依賴于Google的guava,我本項目中引入的swagger2是最高版本,因此引入下面的jar包,否側報錯“Failed to start bean 'documentationPluginsBootstrapper-->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>20.0</version>
</dependency>
編寫swagger的配置文件
@Configuration
@EnableSwagger2
public class SwaggerConf {
@Bean
public Docket petApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//指定從那個包下面開始掃描注解
.apis(RequestHandlerSelectors.basePackage("com.demo"))
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("api文檔")
.version("1.0.0")
.termsOfServiceUrl("localhost:8080/swagger-ui.html")
.description("測試")
.build();
}
}
訪問localhost:8080/swagger-ui.html
遇到問題怎么辦?
org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
原因:
這是因為Springfox使用的路徑匹配是基于AntPathMatcher的,而Spring Boot 2.6.X使用的是PathPatternMatcher
解決方法:
修改application.yaml
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher