一、简介
Swagger 是一个规范和完整的框架,用于生成、描述、调用和可视化 RESTful 风格的 Web 服务。总体目标是使客户端和文件系统作为服务器以同样的速度来更新 。接口的方法,参数和模型紧密集成到服务器端的代码,允许API来始终保持同步。Swagger 让部署管理和使用功能强大的API从未如此简单。
我们的RESTful API就有可能要面对多个开发人员或多个开发团队:IOS开发、Android开发、Web开发等。为了减少与其他团队平时开发期间的频繁沟通成本,传统做法我们会创建一份RESTful API文档来记录所有接口细节,然而这样的做法有以下几个问题:
由于接口众多,并且细节复杂(需要考虑不同的HTTP请求类型、HTTP头部信息、HTTP请求内容等),高质量地创建这份文档本身就是件非常吃力的事,下游的抱怨声不绝于耳;
随着时间推移,不断修改接口实现的时候都必须同步修改接口文档,而文档与代码又处于两个不同的媒介,除非有严格的管理机制,不然很容易导致不一致现象;
而swagger完美的解决了上面的几个问题,并与Spring MVC程序配合组织出强大RESTful API文档。它既可以减少我们创建文档的工作量,同时说明内容又整合入实现代码中,让维护文档和修改代码整合为一体,可以让我们在修改代码逻辑的同时方便的修改文档说明。另外Swagger2也提供了强大的页面测试功能 来调试每个RESTful API。
二、添加Swagger2依赖
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.6.1</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.6.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.6.5</version>
</dependency>
三、创建Swagger2配置类
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import io.swagger.annotations.ApiOperation;
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;
@Configuration //让Spring来加载该类配置
@EnableWebMvc //启用Mvc,非springboot框架需要引入注解@EnableWebMvc
@EnableSwagger2 //启用Swagger2
public class Swagger2Config {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo()).select()
//扫描指定包中的swagger注解
//.apis(RequestHandlerSelectors.basePackage("com.xia.controller"))
//扫描所有有注解的api,用这种方式更灵活
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("基础平台 RESTful APIs")
.description("基础平台 RESTful 风格的接口文档,内容详细,极大的减少了前后端的沟通成本,同时确保代码与文档保持高度一致,极大的减少维护文档的时间。")
.termsOfServiceUrl("http://xiachengwei5.coding.me")
.contact("Xia")
.version("1.0.0")
.build();
}
}
四、编写swagger注解
实体类:
import java.util.Date;
import org.springframework.format.annotation.DateTimeFormat;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
/**
* 人员信息表
* 注解:@ApiModel 和 @ApiModelProperty 用于在通过对象接收参数时在API文档中显示字段的说明
* 注解:@DateTimeFormat 和 @JsonFormat 用于在接收和返回日期格式时将其格式化
* 实体类对应的数据表为: user_info
* @author XiaChengwei
* @date: 2017-07-14 16:45:29
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonIgnoreProperties({ "handler","hibernateLazyInitializer" })
@ApiModel(value ="UserInfo")
public class UserInfo {
@ApiModelProperty(value = "ID")
private Integer id;
@ApiModelProperty(value = "用户登录账号", required = true)
private String userNo;
@ApiModelProperty(value = "姓名", required = true)
private String userName;
@ApiModelProperty(value = "姓名拼音")
private String spellName;
@ApiModelProperty(value = "密码", required = true)
private String password;
@ApiModelProperty(value = "手机号", required = true)
private String userPhone;
@ApiModelProperty(value = "性别")
private Integer userGender;
@ApiModelProperty(value = "记录创建时间")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date createTime;
@ApiModelProperty(value = "记录修改时间")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date updateTime;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo == null ? null : userNo.trim();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
public String getSpellName() {
return spellName;
}
public void setSpellName(String spellName) {
this.spellName = spellName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
public String getUserPhone() {
return userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone == null ? null : userPhone.trim();
}
public Integer getUserGender() {
return userGender;
}
public void setUserGender(Integer userGender) {
this.userGender = userGender;
}
@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@JsonFormat(locale = "zh", timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", userNo=").append(userNo);
sb.append(", userName=").append(userName);
sb.append(", spellName=").append(spellName);
sb.append(", password=").append(password);
sb.append(", userPhone=").append(userPhone);
sb.append(", userGender=").append(userGender);
sb.append(", createTime=").append(createTime);
sb.append(", updateTime=").append(updateTime);
sb.append("]");
return sb.toString();
}
}
控制类:
import java.util.HashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
@RestController
@RequestMapping(value = "/restTest")
@Api(value = "测试信息", description = "测试信息")
public class TestRestCtrl {
@ResponseBody
@RequestMapping(value = "/test", method = RequestMethod.GET)
@ApiOperation(value = "测试接口①")
@ApiImplicitParams({
@ApiImplicitParam(name = "start",value = "开始数", required = true, paramType = "query"),
@ApiImplicitParam(name = "limit",value = "每页展示的记录数", required = true, paramType = "query")
})
public Map<String,Object> test(int start,int limit) {
Map<String,Object> res=new HashMap<String,Object>();
res.put("code", 1);
res.put("resMsg","succed");
return res;
}
@ResponseBody
@RequestMapping(value = "/test2", method = RequestMethod.GET)
@ApiOperation(value = "测试接口②")
public Map<String,Object> test2() {
Map<String,Object> res=new HashMap<String,Object>();
res.put("code", 2);
res.put("resMsg","succed");
return res;
}
}
五、访问
配置完成之后重启服务器,访问地址 http://localhost:8080/项目名/swagger-ui.html
,如:
http://localhost:8080/spring-mvc/swagger-ui.html
访问之后的效果图如下: