手写Api文档的几个痛点:
- 文档需要更新的时候,需要再次发送一份给前端,也就是文档更新交流不及时。
- 接口返回结果不明确
- 不能直接在线测试接口,通常需要使用工具,比如postman
- 接口文档太多,不好管理
Swagger也就是为了解决这个问题,当然也不能说Swagger就一定是完美的,当然也有缺点,最明显的就是代码移入性比较强。
这里讲解的是SpringBoot整合Swagger2,直接生成接口文档的方式。
一、依赖
<dependency>
<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>
二、Swagger配置类
特别要注意的是里面配置了api文件也就是controller包的路径,不然生成的文档扫描不到接口。
import io.swagger.annotations.ApiOperation;
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;
/**
* @author xxy
* @Description
* @date 2018-01-23 22:12:31
*/
@Configuration
public class Swagger2 {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//.apis(RequestHandlerSelectors.basePackage("com.aisino.projects.task.web"))
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot利用swagger构建api文档")
.description("简单优雅的restfun风格,http://blog.csdn.net/saytime")
.termsOfServiceUrl("http://blog.csdn.net/saytime")
.version("1.0")
.build();
}
}
三、开启Swagger
Application.class 加上注解@EnableSwagger2 表示开启Swagger
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@EnableSwagger2
public class SpringbootSwagger2Application {
public static void main(String[] args) {
SpringApplication.run(SpringbootSwagger2Application.class, args);
}
}
访问地址:http://127.0.0.1:8080/app/swagger-ui.html
四、常规用法
示例1:
/**
* 登录 - 获取用户
* @return
*/
@ApiOperation(value="用户登陆", httpMethod = "POST" ,notes="登陆,输入用户名,密码")
@ApiImplicitParams({
@ApiImplicitParam(paramType = "query",name = "username", value = "用户名", required = true, dataType = "String"),
@ApiImplicitParam(paramType = "query",name = "password", value = "密码", required = true, dataType = "String")
})
@RequestMapping(value="/login",method= RequestMethod.POST)
@ResponseBody
public String login(HttpServletRequest request ,String username,String password) {
RetObj retObj = new RetObj();
retObj.setFlag(false);
try {
String password = Base64.getFromBASE64(user.getPassword());
user.setPassword(CryptUtils.byte2hex(CryptUtils.encrypt(LOGIN_KEY,password.getBytes("UTF-8"))));
ShopTaskUser userInfo = userService.getUserInfo(user);
if(userInfo != null) {
request.getSession().setAttribute("shopTaskUserModel", userInfo);
retObj.setFlag(true);
logger.info(userInfo.getUsername() + "登录成功!");
}
} catch (Exception e) {
e.printStackTrace();
}
return JSON.toJSONString(retObj);
}
示例2:
@ApiOperation(value = "查询发票信息",httpMethod = "POST", notes = "根据税号查询极速开票的发票信息")
@ApiImplicitParam(paramType = "query",name = "taxnum", value = "企业税号", required = true, dataType = "String")
@RequestMapping(value = "/queryInvoiceInfo.do")
@ResponseBody
public String queryInvoiceInfo(String taxnum){
if (CommonUtil.isBlank(taxnum)) {
return JSON.toJSONString(CommonUtil.returnMap(JFReturnEnum.PARAM_MISSING,null));
}
log.info("ValetOrderController queryInvoiceInfo参数taxnum:"+taxnum);
InvoiceVO invoiceVO = valetOrderService.queryInvoiceInfo(taxnum);
return JSON.toJSONString(CommonUtil.returnMap(JFReturnEnum.SUCCESS,invoiceVO));
}
示例3:
@ApiOperation(value = "保存收货信息",httpMethod = "POST", notes = "保存收货信息")
// @ApiImplicitParam(name = "receivingInfoVO", value = "收货地址信息", required = true, dataType = "ReceivingInfoVO")
@RequestMapping(value = "/saveReceivingInfo.do")
@ResponseBody
public String saveReceivingInfo(ReceivingInfoVO receivingInfoVO) {
log.info("ValetOrderController saveReceivingInfo参数receivingInfoVO:"+JSON.toJSONString(receivingInfoVO));
boolean updateRes = valetOrderService.saveReceivingInfo(receivingInfoVO);
if(!updateRes) {
return JSON.toJSONString(CommonUtil.returnMap(JFReturnEnum.FAIL,null));
}
return JSON.toJSONString(CommonUtil.returnMap(JFReturnEnum.SUCCESS,null));
}
public class ReceivingInfoVO {
@ApiModelProperty(value = "订单号",required = true)
private String orderNo;
@ApiModelProperty(value = "收货人名称")
private String consigneeName;
@ApiModelProperty(value = "收货人手机号")
private String consigneePhone;
@ApiModelProperty(value = "收货地址所在区域+详细地址")
private String adress;
.........
}
五、Swagger注解
swagger通过注解表明该接口会生成文档,包括接口名、请求方法、参数、返回信息的等等。
- @Api:修饰整个类,描述Controller的作用
- @ApiOperation:描述一个类的一个方法,或者说一个接口
- @ApiParam:单个参数描述
- @ApiModel:用对象来接收参数
- @ApiProperty:用对象接收参数时,描述对象的一个字段
- @ApiResponse:HTTP响应其中1个描述
- @ApiResponses:HTTP响应整体描述
- @ApiIgnore:使用该注解忽略这个API
- @ApiError :发生错误返回的信息
- @ApiImplicitParam:一个请求参数
- @ApiImplicitParams:多个请求参数