Swagger的用法
1.yml配置文件中引入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
2.新建配置文件,配置如下
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.host("localhost:8080")//当前模块的地址
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.***.***.web"))//controller层包名
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("模块名称")
.description("模块接口文档")
.version("1.0")
.build();
}
}
3.重启服务
访问:http://localhost:8080/swagger-ui.html
4.启动报错
4.1 报错1
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Failed to start bean 'documentationPluginsBootstrapper'; nested exception is java.lang.NullPointerException
2023-05-23 16:51:09.394 INFO 16980 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2023-05-23 16:51:09.411 INFO 16980 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2023-05-23 16:51:09.464 ERROR 16980 --- [ main] o.s.boot.SpringApplication : Application run failed
如果启动项目报如下报错或不能访问swagger界面,在yml文件中添加如下配置:
spring:
mvc:
pathmatch:
matching-strategy: ant_path_matcher
4.2 报错2
如果在swagger界面调用后台接口,报错如下
TypeError: Failed to fetch
可以将上述SwaggerConfig 配置文件中的代码去掉或注释即可
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.host("localhost:8080")//当前模块的地址
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.***.***.web"))//controller层包名
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("模块名称")
.description("模块接口文档")
.version("1.0")
.build();
}
一个在学习的开发者,勿喷,欢迎交流