Swagger接口文档
框架层集成Swagger文档
API虽然没有直接的UI,当API体验是十分重要的。API体验指的就是API文档,文档的书写时一个繁琐的体力活儿。大部分开发人员都不太愿意写文档。所以如果框架能够直接支持文档的自动生成,就会大大简化企业维护API文档的工作。
Springboot支持Swagger文档的自动生成。Swagger是基于当前业界Open API 规范开发的工具链。
Springboot中启用Swagger功能
引入依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
</dependency>
添加Swagger配置类
SwaggerConfig
package xyz.staffjoy.account.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
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 api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.basePackage("xyz.staffjoy.account.controller"))
.paths(PathSelectors.any())
.build()
.apiInfo(apiEndPointsInfo())
.useDefaultResponseMessages(false);
}
private ApiInfo apiEndPointsInfo() {
return new ApiInfoBuilder().title("Account REST API")
.description("Staffjoy Account REST API")
.contact(new Contact("bobo", "https://github.com/jskillcloud", "bobo@jskillcloud.com"))
.license("The MIT License")
.licenseUrl("https://opensource.org/licenses/MIT")
.version("V2")
.build();
}
}