一、简介
Swagger2是一款可以生成RESTful接口文档的工具。而且书写起来很方便,开发人员只需维护代码,不用额外书写文档。使用起来更方便,而且呈现的方式很棒。还支持在线测试。
二、SpringBoot集成
我这里时使用的最新版本2.9.2 我这里项目是使用Maven构建的。
1 | <!-- start swagger --> |
配置文件 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50package com.xxx.config;
import org.springframework.beans.factory.annotation.Value;
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;
/**
* @Author :yaxuSong
* @Description: 增加swagger的rest API查看
* @Date: 13:20 2018/8/20
* @Modified by:
*/
2
public class Swagger2Config {
//是否开启swagger,正式环境一般是需要关闭的,可根据springboot的多环境配置进行设置
"${swagger.enabled}") (value =
Boolean swaggerEnabled;
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo())
// 是否开启
.enable(swaggerEnabled).select()
// 扫描的路径包
.apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
// 指定路径处理PathSelectors.any()代表所有的路径
.paths(PathSelectors.any()).build().pathMapping("/");
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("后端服务接口详情")
.description("yaxuSong")
// 作者信息
.contact(new Contact("yaxuSong", "https://weaf.top", "earth@weaf.top"))
.version("1.0.0")
.build();
}
}
部分项目配置不同可能需要配置访问静态文件的路径 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
* @Author :yaxuSong
* @Description: 允许访问Swagger ui静态页面
* @Date: 13:20 2018/8/20
* @Modified by:
*/
public class WebMvcConfig extends WebMvcConfigurerAdapter {
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
//跨域支持
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**");
}
}
设置文档内容
1 | package com.xxx.controller; |
实体对象
1 | package com.xxx.entry.dto; |
三、结果展示
访问路径 http://127.0.0.1:10086/swagger-ui.html#/
设置请求方法的“查看粉丝和关注列表”(设置了请求方法)
未设置请求方法的api
两种设置方法的详细内容(通过点击try it可以进行测试)这里我们也可以通过Postman进行测试
四、相关注解
参考文档:https://swagger.io/