Java效率工具之Swagger2
現(xiàn)代化的研發(fā)組織架構(gòu)中,一個研發(fā)團(tuán)隊(duì)基本包括了產(chǎn)品組、后端組、前端組、APP端研發(fā)、測試組、UI組等,各個細(xì)分組織人員各司其職,共同完成產(chǎn)品的全周期工作。如何進(jìn)行組織架構(gòu)內(nèi)的有效高效溝通就顯得尤其重要。其中,如何構(gòu)建一份合理高效的接口文檔更顯重要。
接口文檔橫貫各個端的研發(fā)人員,但是由于接口眾多,細(xì)節(jié)不一,有時候理解起來并不是那么容易,引起‘內(nèi)戰(zhàn)’也在所難免, 并且維護(hù)也是一大難題。
類似RAP文檔管理系統(tǒng),將接口文檔進(jìn)行在線維護(hù),方便了前端和APP端人員查看進(jìn)行對接開發(fā),但是還是存在以下幾點(diǎn)問題:
- 文檔是接口提供方手動導(dǎo)入的,是靜態(tài)文檔,沒有提供接口測試功能;
- 維護(hù)的難度不小。
Swagger的出現(xiàn)可以完美解決以上傳統(tǒng)接口管理方式存在的痛點(diǎn)。本文介紹Spring Boot整合Swagger2的流程,連帶填坑。
使用流程如下:
1)引入相應(yīng)的maven包:
<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> </dependency> 復(fù)制代碼2)編寫Swagger2的配置類:package com.trace.configuration;import io.swagger.annotations.Api; 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.spi.DocumentationType; import springfox.documentation.spring.web.plugins.Docket; import springfox.documentation.swagger2.annotations.EnableSwagger2;/** * Created by Trace on 2018-05-16.<br/> * Desc: swagger2配置類 */ @SuppressWarnings({"unused"}) @Configuration @EnableSwagger2 public class Swagger2Config {@Value("${swagger2.enable}") private boolean enable;@Bean("UserApis")public Docket userApis() {return new Docket(DocumentationType.SWAGGER_2).groupName("用戶模塊").select().apis(RequestHandlerSelectors.withClassAnnotation(Api.class)).paths(PathSelectors.regex("/user.*")).build().apiInfo(apiInfo()).enable(enable);}@Bean("CustomApis")public Docket customApis() {return new Docket(DocumentationType.SWAGGER_2).groupName("客戶模塊").select().apis(RequestHandlerSelectors.withClassAnnotation(Api.class)).paths(PathSelectors.regex("/custom.*")).build().apiInfo(apiInfo()).enable(enable);}private ApiInfo apiInfo() {return new ApiInfoBuilder().title("XXXXX系統(tǒng)平臺接口文檔").description("提供子模塊1/子模塊2/子模塊3的文檔, 更多請關(guān)注公眾號: 隨行享閱").termsOfServiceUrl("https://xingtian.github.io/trace.github.io/").version("1.0").build();} }復(fù)制代碼
如上可見:
- 通過注解@EnableSwagger2開啟swagger2,apiInfo是接口文檔的基本說明信息,包括標(biāo)題、描述、服務(wù)網(wǎng)址、聯(lián)系人、版本等信息;
- 在Docket創(chuàng)建中,通過groupName進(jìn)行分組,paths屬性進(jìn)行過濾,apis屬性可以設(shè)置掃描包,或者通過注解的方式標(biāo)識;通過enable屬性,可以在application-{profile}.properties文件中設(shè)置相應(yīng)值,主要用于控制生產(chǎn)環(huán)境不生成接口文檔。
3)controller層類和方法添加相關(guān)注解
package com.trace.controller;import com.trace.bind.ResultModel; import com.trace.entity.po.Area; import com.trace.entity.po.User; import com.trace.service.UserService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiImplicitParam; import io.swagger.annotations.ApiImplicitParams; import io.swagger.annotations.ApiOperation; import org.springframework.web.bind.annotation.*; import javax.annotation.Resource; import java.util.List;/*** Created by Trace on 2017-12-01.<br/>* Desc: 用戶管理controller*/ @SuppressWarnings("unused") @RestController @RequestMapping("/user") @Api(tags = "用戶管理") public class UserController {@Resource private UserService userService;@GetMapping("/query/{id}")@ApiOperation("通過ID查詢")@ApiImplicitParam(name = "id", value = "用戶ID", required = true, dataType = "int", paramType = "path")public ResultModel<User> findById(@PathVariable int id) {User user = userService.findById(id);return ResultModel.success("id查詢成功", user);}@GetMapping("/query/ids")@ApiOperation("通過ID列表查詢")public ResultModel<List<User>> findByIdIn(int[] ids) {List<User> users = userService.findByIdIn(ids);return ResultModel.success("in查詢成功", users);}@GetMapping("/query/user")@ApiOperation("通過用戶實(shí)體查詢")public ResultModel<List<User>> findByUser(User user) {List<User> users = userService.findByUser(user);return ResultModel.success("通過實(shí)體查詢成功", users);}@GetMapping("/query/all")@ApiOperation("查詢所有用戶")public ResultModel<List<User>> findAll() {List<User> users = userService.findAll();return ResultModel.success("全體查找成功", users);}@GetMapping("/query/username")@ApiOperation("通過用戶名稱模糊查詢")@ApiImplicitParam(name = "userName", value = "用戶名稱")public ResultModel<List<User>> findByUserName(String userName) {List<User> users = userService.findByUserName(userName);return ResultModel.success(users);}@PostMapping("/insert")@ApiOperation("新增默認(rèn)用戶")public ResultModel<Integer> insert() {User user = new User();user.setUserName("zhongshiwen");user.setNickName("zsw");user.setRealName("鐘仕文");user.setPassword("zsw123456");user.setGender("男");Area area = new Area();area.setLevel((byte) 5);user.setArea(area);userService.save(user);return ResultModel.success("新增用戶成功", user.getId());}@PutMapping("/update")@ApiOperation("更新用戶信息")public ResultModel<Integer> update(User user) {int row = userService.update(user);return ResultModel.success(row);}@PutMapping("/update/status")@ApiOperation("更新單個用戶狀態(tài)")@ApiImplicitParams({@ApiImplicitParam(name = "id", value = "用戶ID", required = true),@ApiImplicitParam(name = "status", value = "狀態(tài)", required = true)})public ResultModel<User> updateStatus(int id, byte status) {User user = userService.updateStatus(id, status);return ResultModel.success(user);}@DeleteMapping("/delete")@ApiOperation("刪除單個用戶")@ApiImplicitParam(value = "用戶ID", required = true)public ResultModel<Integer> delete(int id) {return ResultModel.success(userService.delete(id));} }復(fù)制代碼4)返回對象ResultModel
package com.trace.bind;import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Getter; import lombok.Setter;/** * Created by Trace on 2017-12-01.<br/> * Desc: 接口返回結(jié)果對象 */ @SuppressWarnings("unused") @Getter @Setter @ApiModel(description = "返回結(jié)果") public final class ResultModel<T> {@ApiModelProperty("是否成功: true or false")private boolean result;@ApiModelProperty("描述性原因")private String message;@ApiModelProperty("業(yè)務(wù)數(shù)據(jù)")private T data;private ResultModel(boolean result, String message, T data) {this.result = result;this.message = message;this.data = data;}public static<T> ResultModel<T> success(T data) {return new ResultModel<>(true, "SUCCESS", data);}public static<T> ResultModel<T> success(String message, T data) {return new ResultModel<>(true, message, data);}public static ResultModel failure() {return new ResultModel<>(false, "FAILURE", null);}public static ResultModel failure(String message) {return new ResultModel<>(false, message, null);} } 復(fù)制代碼5)ApiModel屬性對象 -- User實(shí)體
package com.trace.entity.po;import com.trace.mapper.base.NotPersistent; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.List;/*** Created by Trace on 2017-12-01.<br/>* Desc: 用戶表tb_user*/ @SuppressWarnings("unused") @Data @NoArgsConstructor @AllArgsConstructor @ApiModel public class User {@ApiModelProperty("用戶ID") private Integer id;@ApiModelProperty("賬戶名") private String userName;@ApiModelProperty("用戶昵稱") private String nickName;@ApiModelProperty("真實(shí)姓名") private String realName;@ApiModelProperty("身份證號碼") private String identityCard;@ApiModelProperty("性別") private String gender;@ApiModelProperty("出生日期") private LocalDate birth;@ApiModelProperty("手機(jī)號碼") private String phone;@ApiModelProperty("郵箱") private String email;@ApiModelProperty("密碼") private String password;@ApiModelProperty("用戶頭像地址") private String logo;@ApiModelProperty("賬戶狀態(tài) 0:正常; 1:凍結(jié); 2:注銷") private Byte status;@ApiModelProperty("個性簽名") private String summary;@ApiModelProperty("用戶所在區(qū)域碼") private String areaCode;@ApiModelProperty("注冊時間") private LocalDateTime registerTime;@ApiModelProperty("最近登錄時間") private LocalDateTime lastLoginTime;@NotPersistent @ApiModelProperty(hidden = true)private transient Area area; //用戶所在地區(qū)@NotPersistent @ApiModelProperty(hidden = true)private transient List<Role> roles; //用戶角色列表 } 復(fù)制代碼簡單說下Swagger2幾個重要注解:
@Api:用在請求的類上,表示對類的說明??
- tags "說明該類的作用,可以在UI界面上看到的注解"?
- value "該參數(shù)沒什么意義,在UI界面上也看到,所以不需要配置"?
@ApiOperation:用在請求的方法上,說明方法的用途、作用?
- value="說明方法的用途、作用"?
- notes="方法的備注說明"?
@ApiImplicitParams:用在請求的方法上,表示一組參數(shù)說明?
@ApiImplicitParam:用在@ApiImplicitParams注解中,指定一個請求參數(shù)的各個方面
- value:參數(shù)的漢字說明、解釋?
- required:參數(shù)是否必須傳?
- paramType:參數(shù)放在哪個地方?
- dataType:參數(shù)類型,默認(rèn)String,其它值dataType="Integer"?
- defaultValue:參數(shù)的默認(rèn)值?
@ApiResponses:用在請求的方法上,表示一組響應(yīng)?
@ApiResponse:用在@ApiResponses中,一般用于表達(dá)一個錯誤的響應(yīng)信息?
- code:數(shù)字,例如400?
- message:信息,例如"請求參數(shù)沒填好"?
- response:拋出異常的類?
@ApiModel:主要有兩種用途:
- 用于響應(yīng)類上,表示一個返回響應(yīng)數(shù)據(jù)的信息?
- 入?yún)?shí)體:使用@RequestBody這樣的場景, 請求參數(shù)無法使用@ApiImplicitParam注解進(jìn)行描述的時候
@ApiModelProperty:用在屬性上,描述響應(yīng)類的屬性
最終呈現(xiàn)結(jié)果:
如前所述:通過maven導(dǎo)入了swagger-ui:
<dependency><groupId>io.springfox</groupId><artifactId>springfox-swagger-ui</artifactId><version>2.7.0</version> </dependency> 復(fù)制代碼那么,啟動應(yīng)用后,會自動生成http://{root-path}/swagger-ui.html頁面,訪問后,效果如下所示:
可以在線測試接口,如通過ID查詢的接口/user/query/{id}
全文完!
下一篇:Java效率工具之Lombok
總結(jié)
以上是生活随笔為你收集整理的Java效率工具之Swagger2的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Git 几个常用操作
- 下一篇: 深入学习Java多线程——并发机制底层实