1 简介
当我们在创建REST API时,需要有清晰的API说明文档,用于提供开发人员阅读和使用API。然而,在开发过程中每次更新API,需要同步更新API文档,这无疑是加重了开发工作量。
Swagger是一个用于快速构建API文档的工具,可以自己从代码中生成API说明文档。
下面将一步步描述如何向spring REST web service项目中引入swagger。
2 新建Spring Boot 工程
参考
Build a REST API with Spring 4 and Java Config article
Building a RESTful Web Service
spring boot 2.0.2
3 向Maven的配置pom.xml中添加依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
<scope>compile</scope>
</dependency>
4 新建一个配置文件
SwaggerConfig.java
@Configuration
@EnableSwagger2
public class SwaggerConfig extends WebMvcConfigurationSupport {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.any())
.build();
}
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
对于本应用,我们创建了一个Docket
bean, 一个springfox Docket
实例提供原始的API配置,包含默认的配置和方法。
在这个配置文件中,@EnableSwagger2
注解用于开启该类的Swagger支持。select()
方法在Docket
bean的实例中返回ApiSelectorBuilder
,它提供了api()
方法和 path()
方法来过滤controller和谓语的方法。
5 访问api-doc
原始以json描述的 API
http://localhost:8080/v2/api-docs
6 访问UI界面
http://localhost:8080/swagger-ui.html
参考:
https://springframework.guru/spring-boot-restful-api-documentation-with-swagger-2/