使用Swagger自動生成API說明文件
專案環境
jdk1.8
spring4.1.7
tomcat8.5.37
整合步驟
1.在pom檔案中新增swagger依賴
<dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger2</artifactId> <version>2.4.0</version> </dependency> <dependency> <groupId>io.springfox</groupId> <artifactId>springfox-swagger-ui</artifactId> <version>2.4.0</version> <exclusions> <exclusion> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.google.guava</groupId> <artifactId>guava</artifactId> <version>19.0</version> </dependency> <dependency> <groupId>org.mapstruct</groupId> <artifactId>mapstruct-jdk8</artifactId> <version>1.1.0.Final</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.verson}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.verson}</version> <exclusions> <exclusion> <artifactId>jackson-annotations</artifactId> <groupId>com.fasterxml.jackson.core</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.verson}</version> </dependency>
2.建立swagger配置類:SwaggerConfig.java
@EnableSwagger2 @ComponentScan(basePackages = {"cn.smbms.controller"}) @Configuration public class SwaggerConfig extends WebMvcConfigurationSupport { @Bean public Docket createRestApi() { return new Docket(DocumentationType.SWAGGER_2) .apiInfo(apiInfo()) .select() .apis(RequestHandlerSelectors.any()) .paths(PathSelectors.any()) .build(); } private ApiInfo apiInfo() { return new ApiInfoBuilder() .title("超市訂單管理系統API") .termsOfServiceUrl("") .contact("") .version("1.0") .build(); } }
3.修改Spring MVC配置檔案 springmvc-servlet.xml
<mvc:default-servlet-handler/> //這個一定要加上否則訪問不到swagger-ui.html
<context:component-scan base-package="cn.smbms.controller"></context:component-scan>
4.在工程中使用swagger
建立LoginController:
@Api(value="API") @Controller public class LoginController { @Resource private UserService userService; @ApiOperation(value = "系統管理員登入", httpMethod = "POST", protocols = "HTTP",produces = "application/json", response = Object.class,notes = "管理員登入"+ "<p>登入成功:flag = ‘true’ | 使用者名稱或密碼錯誤:flag = ‘false’ </p>" ) @RequestMapping(value="/dologin.html",method=RequestMethod.POST) @ResponseBody public Object doLogin( @ApiParam(required = true, name = "userCode", value ="使用者名稱") @RequestParam String userCode, @ApiParam(required = true, name = "userPassword", value ="使用者密碼") @RequestParam String userPassword)throws Exception{ Map<String,String> map = new HashMap<String,String>(); User user =userService.login(userCode, userPassword); if(null!=user){ map.put("flag", "true"); }else{ map.put("flag","false"); } return JSON.toJSONString(map); } }
建立UserController:
@Api(value="API")
@Controller
@RequestMapping("/sys/user") //http://localhost:8080/smbms/sys/user/add.html
public class UserController {
@Resource
private UserService userService;
@ApiOperation(value="新增使用者",httpMethod="POST",produces="application/json",
protocols = "HTTP",response = Object.class,notes = "管理員登入"+
"<p>新增使用者成功:flag = ‘true’ | 新增使用者失敗:flag = ‘false’ </p>" )
@RequestMapping(value="/add.html",method=RequestMethod.POST)
@ResponseBody
public Object addSave(
@RequestBody User user){
Map<String,String> map = new HashMap<String, String>();
user.setCreatedBy(1);
user.setCreationDate(new Date());
if(userService.add(user)){
map.put("flag", "true");
}else{
map.put("flag", "false");
}
return JSON.toJSONString(map);
}
}
因為以上的 addSave方法引數為一個User物件,所以需要在User類中標註swagger註解以說明屬性
@ApiModel(value="User",description="使用者資訊")
public class User {
@ApiModelProperty("[非必填] 使用者ID")
private Integer id; //id
@ApiModelProperty("[必填] 使用者名稱")
private String userCode;
@ApiModelProperty("[非必填] 使用者姓名")
private String userName;
@ApiModelProperty("[必填] 使用者密碼,長度不能小於6位")
private String userPassword;
@ApiModelProperty("[非必填] 使用者出生日期")
private Date birthday;
@ApiModelProperty("[必填] 使用者性別")
private Integer gender;
@ApiModelProperty("[必填] 使用者手機號")
private String phone;
@ApiModelProperty("[非必填] 使用者地址")
private String address;
@ApiModelProperty("[必填] 使用者角色 1.管理員 2.部門經理 3.普通員工")
private Integer userRole;
@ApiModelProperty("[非必填]後端從session中獲取")
private Integer createdBy;
@ApiModelProperty("[非必填]後端獲取系統當前日期")
private Date creationDate;
@ApiModelProperty("[非必填]後端從session中獲取")
private Integer modifyBy;
@ApiModelProperty("[非必填]後端獲取系統當前日期")
private Date modifyDate;
private String userRoleName;
private String idPicPath;
private String workPicPath;
public String getWorkPicPath() {
return workPicPath;
}
public void setWorkPicPath(String workPicPath) {
this.workPicPath = workPicPath;
}
public String getIdPicPath() {
return idPicPath;
}
public void setIdPicPath(String idPicPath) {
this.idPicPath = idPicPath;
}
public User(){}
public User(Integer id,String userCode,String userName,String userPassword,Integer gender,Date birthday,String phone,
String address,Integer userRole,Integer createdBy,Date creationDate,Integer modifyBy,Date modifyDate){
this.id = id;
this.userCode = userCode;
this.userName = userName;
this.userPassword = userPassword;
this.gender = gender;
this.birthday = birthday;
this.phone = phone;
this.address = address;
this.userRole = userRole;
this.createdBy = createdBy;
this.creationDate = creationDate;
this.modifyBy = modifyBy;
this.modifyDate = modifyDate;
}
public String getUserRoleName() {
return userRoleName;
}
public void setUserRoleName(String userRoleName) {
this.userRoleName = userRoleName;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserCode() {
return userCode;
}
public void setUserCode(String userCode) {
this.userCode = userCode;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public Integer getGender() {
return gender;
}
public void setGender(Integer gender) {
this.gender = gender;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Integer getUserRole() {
return userRole;
}
public void setUserRole(Integer userRole) {
this.userRole = userRole;
}
public Integer getCreatedBy() {
return createdBy;
}
public void setCreatedBy(Integer createdBy) {
this.createdBy = createdBy;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public Integer getModifyBy() {
return modifyBy;
}
public void setModifyBy(Integer modifyBy) {
this.modifyBy = modifyBy;
}
public Date getModifyDate() {
return modifyDate;
}
public void setModifyDate(Date modifyDate) {
this.modifyDate = modifyDate;
}
}
說明:以上的login和addSave方法呼叫了邏輯層的業務方法,大家可以使用虛擬碼模擬業務方法即可。只需按照以上內容建立三個類即可。
上傳到伺服器訪問:swagger-ui.html
直接通過tomcat訪問:
http://IP:port/{context-path}/swagger-ui.html
生產環境下,只開放80埠,通過Tomcat無法訪問Swagger
所以只能通過Nginx進行Swagger的訪問
修改nginx.conf :需要註釋掉root節 以及 .html的快取
http://IP/{context-path}/swagger-ui.html
swagger註解說明
下面針對以上內容使用到的swagger註解進行說明:
@Api 表明可供swagger展示的介面類(標註在類上)
@ApiOperation描述API方法(用在方法上)
@ApiOperation(value = “介面說明”,
httpMethod = “介面請求方式”,
produces = “介面返回值的具體型別”,
response = 介面返回的物件,
protocols = “通訊協議(e.g:http, https)”,
notes = “介面釋出說明")
@ApiParam單個引數描述
@ApiModel
用物件接收引數(用在類上面)
@ApiModelProperty
用物件接收引數時,描述物件的一個欄位(用在屬性上面)