現代化的研發組織架構中,一個研發團隊基本包括了產品組、後端組、前端組、APP端研發、測試組、UI組等,各個細分組織人員各司其職,共同完成產品的全週期工做。如何進行組織架構內的有效高效溝通就顯得尤爲重要。其中,如何構建一份合理高效的接口文檔更顯重要。
html
接口文檔橫貫各個端的研發人員,可是因爲接口衆多,細節不一,有時候理解起來並非那麼容易,引發‘內戰’也在所不免, 而且維護也是一大難題。前端
相似RAP文檔管理系統,將接口文檔進行在線維護,方便了前端和APP端人員查看進行對接開發,可是仍是存在如下幾點問題:java
Swagger的出現能夠完美解決以上傳統接口管理方式存在的痛點。本文介紹Spring Boot整合Swagger2的流程,連帶填坑。
git
使用流程以下:github
1)引入相應的maven包:web
<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>
複製代碼
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系統平臺接口文檔")
.description("提供子模塊1/子模塊2/子模塊3的文檔, 更多請關注公衆號: 隨行享閱")
.termsOfServiceUrl("https://xingtian.github.io/trace.github.io/")
.version("1.0")
.build();
}
}複製代碼
如上可見:spring
3)controller層類和方法添加相關注解後端
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("經過用戶實體查詢")
public ResultModel<List<User>> findByUser(User user) {
List<User> users = userService.findByUser(user);
return ResultModel.success("經過實體查詢成功", 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("新增默認用戶")
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("更新單個用戶狀態")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用戶ID", required = true),
@ApiImplicitParam(name = "status", value = "狀態", 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));
}
}複製代碼
4)返回對象ResultModelapi
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: 接口返回結果對象
*/
@SuppressWarnings("unused")
@Getter @Setter @ApiModel(description = "返回結果")
public final class ResultModel<T> {
@ApiModelProperty("是否成功: true or false")
private boolean result;
@ApiModelProperty("描述性緣由")
private String message;
@ApiModelProperty("業務數據")
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);
}
}
複製代碼
5)ApiModel屬性對象 -- User實體bash
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("真實姓名") private String realName;
@ApiModelProperty("身份證號碼") private String identityCard;
@ApiModelProperty("性別") private String gender;
@ApiModelProperty("出生日期") private LocalDate birth;
@ApiModelProperty("手機號碼") private String phone;
@ApiModelProperty("郵箱") private String email;
@ApiModelProperty("密碼") private String password;
@ApiModelProperty("用戶頭像地址") private String logo;
@ApiModelProperty("帳戶狀態 0:正常; 1:凍結; 2:註銷") private Byte status;
@ApiModelProperty("個性簽名") private String summary;
@ApiModelProperty("用戶所在區域碼") private String areaCode;
@ApiModelProperty("註冊時間") private LocalDateTime registerTime;
@ApiModelProperty("最近登陸時間") private LocalDateTime lastLoginTime;
@NotPersistent @ApiModelProperty(hidden = true)
private transient Area area; //用戶所在地區
@NotPersistent @ApiModelProperty(hidden = true)
private transient List<Role> roles; //用戶角色列表
}
複製代碼
簡單說下Swagger2幾個重要註解:
@Api:用在請求的類上,表示對類的說明
@ApiOperation:用在請求的方法上,說明方法的用途、做用
@ApiImplicitParams:用在請求的方法上,表示一組參數說明
@ApiImplicitParam:用在@ApiImplicitParams註解中,指定一個請求參數的各個方面
@ApiResponses:用在請求的方法上,表示一組響應
@ApiResponse:用在@ApiResponses中,通常用於表達一個錯誤的響應信息
@ApiModel:主要有兩種用途:
@ApiModelProperty:用在屬性上,描述響應類的屬性
最終呈現結果:
如前所述:經過maven導入了swagger-ui:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
複製代碼
那麼,啓動應用後,會自動生成http://{root-path}/swagger-ui.html頁面,訪問後,效果以下所示:
能夠在線測試接口,如經過ID查詢的接口/user/query/{id}
全文完!
下一篇:Java效率工具之Lombok