Spring Boot 集成 Swagger2 显示字段说明
给 Spring Boot 接口接入 Swagger2(springfox),自动生成接口文档,并通过 @ApiModelProperty 等注解在文档里展示字段说明。
添加依赖
1<dependency>
2 <groupId>io.springfox</groupId>
3 <artifactId>springfox-swagger2</artifactId>
4 <version>2.9.2</version>
5</dependency>
6<dependency>
7 <groupId>io.springfox</groupId>
8 <artifactId>springfox-swagger-ui</artifactId>
9 <version>2.9.2</version>
10</dependency>
Swagger 配置
1import org.springframework.beans.factory.annotation.Value;
2import org.springframework.context.annotation.Bean;
3import org.springframework.context.annotation.Configuration;
4import springfox.documentation.builders.ApiInfoBuilder;
5import springfox.documentation.builders.PathSelectors;
6import springfox.documentation.builders.RequestHandlerSelectors;
7import springfox.documentation.service.ApiInfo;
8import springfox.documentation.service.Contact;
9import springfox.documentation.spi.DocumentationType;
10import springfox.documentation.spring.web.plugins.Docket;
11import springfox.documentation.swagger2.annotations.EnableSwagger2;
12
13@Configuration
14@EnableSwagger2
15public class SwaggerConfiguration {
16 @Value("${swagger.enabled}")
17 private boolean enable;
18
19 @Bean
20 public Docket createRestApi() {
21 return new Docket(DocumentationType.SWAGGER_2)
22 .apiInfo(apiInfo())
23 .enable(enable)
24 .select()
25 .apis(RequestHandlerSelectors.basePackage("com.fecred.villagedoctor.controller"))
26 .paths(PathSelectors.any())
27 .build();
28 }
29
30 @Bean
31 public Docket healthApi() {
32 return new Docket(DocumentationType.SWAGGER_2)
33 .groupName("分组名称")
34 .apiInfo(apiInfo())
35 .enable(enable)
36 .select()
37 // 分组的 controller 层
38 .apis(RequestHandlerSelectors.basePackage("com.xxx.controller"))
39 .paths(PathSelectors.regex(".*/health/.*"))
40 .build();
41 }
42
43 private ApiInfo apiInfo() {
44 return new ApiInfoBuilder()
45 .title("标题")
46 .description("一般描述信息")
47 .termsOfServiceUrl("http://localhost:8999/")
48 .contact(new Contact("联系人", "邮箱", "邮箱"))
49 .version("1.0")
50 .build();
51 }
52}
swagger.enabled 配置在配置文件里,生产环境可以设为 false 关闭文档入口。
前后端响应工具类
用 @ApiModelProperty 标注每个字段的含义,Swagger 文档中会直接展示:
1import io.swagger.annotations.ApiModelProperty;
2import lombok.Data;
3
4@Data
5public class Result<T> {
6 @ApiModelProperty(value = "状态值")
7 private int code;
8 @ApiModelProperty(value = "提示信息")
9 private String message;
10 @ApiModelProperty(value = "结果")
11 private T payload;
12
13 private Result<T> code(int code) {
14 this.code = code;
15 return this;
16 }
17
18 private Result<T> message(String message) {
19 this.message = message;
20 return this;
21 }
22
23 private Result<T> payload(T payload) {
24 this.payload = payload;
25 return this;
26 }
27
28 public static <T> Result<T> ok() {
29 return new Result<T>().code(ResultCode.SUCCESS.getCode()).message(ResultCode.SUCCESS.getMessage()).payload(null);
30 }
31
32 public static <T> Result<T> ok(T payload) {
33 return new Result<T>().code(ResultCode.SUCCESS.getCode()).message(ResultCode.SUCCESS.getMessage()).payload(payload);
34 }
35
36 public static <T> Result<T> fail() {
37 return new Result<T>().code(ResultCode.FAIL.getCode()).message(ResultCode.FAIL.getMessage()).payload(null);
38 }
39
40 public static <T> Result<T> result(int code, String message, T payload) {
41 return new Result<T>().code(code).message(message).payload(payload);
42 }
43}
状态码
1@Getter
2public enum ResultCode {
3 // 成功
4 SUCCESS(20000, "成功"),
5 // 失败
6 FAIL(40000, "失败"),
7 // 未认证(签名错误)
8 UNAUTHORIZED(40001, "未认证(签名错误)"),
9 // 接口不存在
10 NOT_FOUND(40004, "接口不存在"),
11 // 服务器内部错误
12 INTERNAL_SERVER_ERROR(50000, "服务器内部错误"),
13 // TOKEN已过期
14 TOKEN_INVAILD(10001, "TOKEN已过期"),
15 // TOKEN无效
16 TOKEN_NOTFOUND(10002, "TOKEN无效");
17 private final int code;
18 private final String message;
19
20 ResultCode(int code, String message) {
21 this.code = code;
22 this.message = message;
23 }
24}
Controller 层使用
1@GetMapping(value = "/detail")
2@ApiOperation(value = "根据id查询用户")
3public Result<User> detail(@RequestParam("userId") Long userId) {
4 log.info("根据userId查询用户信息【{}】", userId);
5 User user = userService.findByUserId(userId);
6 log.info("用户信息【{}】", user.toString());
7 return Result.ok(user);
8}
@ApiOperation 描述接口用途;参数对象(如 User)里的字段加上 @ApiModelProperty 后,文档中会一并展示。
PageInfo 封装
用于 PageHelper 分页结果展示属性值:
1import com.github.pagehelper.Page;
2import io.swagger.annotations.ApiModelProperty;
3import lombok.Data;
4
5import java.util.Collection;
6import java.util.List;
7
8@Data
9public class MyPageInfo<T> {
10 @ApiModelProperty(value = "当前页")
11 private int pageNum;
12 @ApiModelProperty(value = "每页的数量")
13 private int pageSize;
14 @ApiModelProperty(value = "当前页的数量")
15 private int size;
16 /**
17 * 由于startRow和endRow不常用,这里说个具体的用法
18 * 可以在页面中"显示startRow到endRow 共size条数据"
19 */
20 @ApiModelProperty(value = "当前页面第一个元素在数据库中的行号")
21 private int startRow;
22 @ApiModelProperty(value = "当前页面最后一个元素在数据库中的行号")
23 private int endRow;
24 @ApiModelProperty(value = "总页数")
25 private int pages;
26 @ApiModelProperty(value = "前一页")
27 private int prePage;
28 @ApiModelProperty(value = "下一页")
29 private int nextPage;
30 @ApiModelProperty(value = "是否为第一页")
31 private boolean firstPage = false;
32 @ApiModelProperty(value = "是否为最后一页")
33 private boolean lastPage = false;
34 @ApiModelProperty(value = "是否有前一页")
35 private boolean hasPreviousPage = false;
36 @ApiModelProperty(value = "是否有下一页")
37 private boolean hasNextPage = false;
38 @ApiModelProperty(value = "导航页码数")
39 private int navigatePages;
40 @ApiModelProperty(value = "所有导航页号")
41 private int[] navigatepageNums;
42 @ApiModelProperty(value = "导航条上的第一页")
43 private int navigateFirstPage;
44 @ApiModelProperty(value = "导航条上的最后一页")
45 private int navigateLastPage;
46 @ApiModelProperty(value = "总页数")
47 private long total;
48 @ApiModelProperty(value = "结果集")
49 private List<T> list;
50
51 public MyPageInfo() {
52 this.firstPage = false;
53 this.lastPage = false;
54 this.hasPreviousPage = false;
55 this.hasNextPage = false;
56 }
57
58 public MyPageInfo(List<T> list) {
59 this(list, 8);
60 this.list = list;
61 if (list instanceof Page) {
62 this.total = ((Page) list).getTotal();
63 } else {
64 this.total = (long) list.size();
65 }
66 }
67
68 public MyPageInfo(List<T> list, int navigatePages) {
69 this.firstPage = false;
70 this.lastPage = false;
71 this.hasPreviousPage = false;
72 this.hasNextPage = false;
73 if (list instanceof Page) {
74 Page page = (Page) list;
75 this.pageNum = page.getPageNum();
76 this.pageSize = page.getPageSize();
77 this.pages = page.getPages();
78 this.size = page.size();
79 if (this.size == 0) {
80 this.startRow = 0;
81 this.endRow = 0;
82 } else {
83 this.startRow = page.getStartRow() + 1;
84 this.endRow = this.startRow - 1 + this.size;
85 }
86 } else if (list instanceof Collection) {
87 this.pageNum = 1;
88 this.pageSize = list.size();
89 this.pages = this.pageSize > 0 ? 1 : 0;
90 this.size = list.size();
91 this.startRow = 0;
92 this.endRow = list.size() > 0 ? list.size() - 1 : 0;
93 }
94
95 if (list instanceof Collection) {
96 this.navigatePages = navigatePages;
97 this.calcNavigatepageNums();
98 this.calcPage();
99 this.judgePageBoudary();
100 }
101
102 }
103
104 private void calcNavigatepageNums() {
105 // 当总页数小于或等于导航页码数时
106 if (pages <= navigatePages) {
107 navigatepageNums = new int[pages];
108 for (int i = 0; i < pages; i++) {
109 navigatepageNums[i] = i + 1;
110 }
111 } else { // 当总页数大于导航页码数时
112 navigatepageNums = new int[navigatePages];
113 int startNum = pageNum - navigatePages / 2;
114 int endNum = pageNum + navigatePages / 2;
115
116 if (startNum < 1) {
117 startNum = 1;
118 // 最前navigatePages页
119 for (int i = 0; i < navigatePages; i++) {
120 navigatepageNums[i] = startNum++;
121 }
122 } else if (endNum > pages) {
123 endNum = pages;
124 // 最后navigatePages页
125 for (int i = navigatePages - 1; i >= 0; i--) {
126 navigatepageNums[i] = endNum--;
127 }
128 } else {
129 // 所有中间页
130 for (int i = 0; i < navigatePages; i++) {
131 navigatepageNums[i] = startNum++;
132 }
133 }
134 }
135 }
136
137 private void calcPage() {
138 if (this.navigatepageNums != null && this.navigatepageNums.length > 0) {
139 this.navigateFirstPage = this.navigatepageNums[0];
140 this.navigateLastPage = this.navigatepageNums[this.navigatepageNums.length - 1];
141 if (this.pageNum > 1) {
142 this.prePage = this.pageNum - 1;
143 }
144
145 if (this.pageNum < this.pages) {
146 this.nextPage = this.pageNum + 1;
147 }
148 }
149
150 }
151
152 private void judgePageBoudary() {
153 this.firstPage = this.pageNum == 1;
154 this.lastPage = this.pageNum == this.pages || this.pages == 0;
155 this.hasPreviousPage = this.pageNum > 1;
156 this.hasNextPage = this.pageNum < this.pages;
157 }
158}
PageHelper 配合使用
1@GetMapping(value = "/list")
2@ApiOperation(value = "获取用户列表")
3public ResponseData<MyPageInfo<User>> getList(@RequestParam(value = "page", defaultValue = "1") Integer page, @RequestParam(value = "size", defaultValue = "10") Integer size) {
4 PageHelper.startPage(page, size);
5 List<User> list = userService.getList();
6 log.info("查询用户列表记录数为:【{}】", list.size());
7 MyPageInfo<User> pageInfo = new MyPageInfo<>(list);
8 return ResultGenerator.successResult(pageInfo);
9}
