本文接着前面的继续,介绍如何快速接入Swagger
Spring Boot入门系列
- Spring Boot七分钟快速实践
- Spring Boot & MyBatis
- Spring Boot & Redis
- Spring Boot & Swagger
- Spring Boot & 单元测试
- Spring Boot & Actuator
- Spring Boot Admin
两步接入
- pom.xml
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
- 代码配置
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
}
展示地址
- 数据接口 http://localhost:8080/swagger-ui.html
- UI http://localhost:8080/v2/api-docs
- http://localhost:8080 指的是当前项目
其他配置
- 限制开发环境展示,使用Spring条件注入特性
@Profile("dev")
@Configuration
@EnableSwagger2
@Profile("dev")
public class SwaggerConfig {
- 测试环境启动命令如下
java -jar boot-web-2.1.2.RELEASE.jar -Dspring.profiles.active=dev
- 限制部分接口
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.tenmao.mvc.controller"))
.paths(PathSelectors.ant("/api/*"))
.build();
}
- 自定义文档信息
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("com.tenmao.mvc.controller"))
.paths(PathSelectors.ant("/api/*"))
.build()
// 这里有一个调用
.apiInfo(apiInfo());
}
private ApiInfo apiInfo() {
return new ApiInfo(
"十毛API",
"十毛API文档",
"1.0",
"Terms of service",
new Contact("tenmao", "https://www.jianshu.com/u/518bde83a9bc", "tenmao@example.com"),
"License of API", "API license URL", Collections.emptyList());
}
参考
- https://www.baeldung.com/swagger-2-documentation-for-spring-rest-api
- 生产环境中禁用swagger
- 代码自动生成文档 - Springfox(Swagger2)
本文由 创作,采用 知识共享署名4.0 国际许可协议进行许可。本站文章除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为: 2020/05/16 13:41