Swagger接口文档
框架层集成 Swagger 文档
API 虽然没有直接的 UI,当 API 体验是十分重要的。API 体验指的就是 API 文档,文档的书写时一个繁琐的体力活儿。大部分开发人员都不太愿意写文档。所以如果框架能够直接支持文档的自动生成,就会大大简化企业维护 API 文档的工作。
SpringBoot 支持 Swagger 文档的自动生成。Swagger 是基于当前业界 Open API 规范开发的工具链。
SpringBoot 中启用 Swagger 功能
引入依赖
1 <dependency>
2 <groupId>io.springfox</groupId>
3 <artifactId>springfox-swagger2</artifactId>
4 </dependency>
5 <dependency>
6 <groupId>io.springfox</groupId>
7 <artifactId>springfox-swagger-ui</artifactId>
8 </dependency>
添加 Swagger 配置类
SwaggerConfig
1package xyz.staffjoy.account.config;
2
3import org.springframework.context.annotation.Bean;
4import org.springframework.context.annotation.Configuration;
5import springfox.documentation.builders.ApiInfoBuilder;
6import springfox.documentation.builders.PathSelectors;
7import springfox.documentation.builders.RequestHandlerSelectors;
8import springfox.documentation.service.ApiInfo;
9import springfox.documentation.service.Contact;
10import springfox.documentation.spi.DocumentationType;
11import springfox.documentation.spring.web.plugins.Docket;
12import springfox.documentation.swagger2.annotations.EnableSwagger2;
13
14@Configuration
15@EnableSwagger2
16public class SwaggerConfig {
17 @Bean
18 public Docket api() {
19 return new Docket(DocumentationType.SWAGGER_2)
20 .select()
21 .apis(RequestHandlerSelectors.basePackage("xyz.staffjoy.account.controller"))
22 .paths(PathSelectors.any())
23 .build()
24 .apiInfo(apiEndPointsInfo())
25 .useDefaultResponseMessages(false);
26 }
27
28 private ApiInfo apiEndPointsInfo() {
29 return new ApiInfoBuilder().title("Account REST API")
30 .description("Staffjoy Account REST API")
31 .contact(new Contact("bobo", "https://github.com/jskillcloud", "bobo@jskillcloud.com"))
32 .license("The MIT License")
33 .licenseUrl("https://opensource.org/licenses/MIT")
34 .version("V2")
35 .build();
36 }
37}
38