手写Api文档的几个痛点:
- 文档需要更新的时候,需要再次发送一份给前端,也就是文档更新交流不及时。
- 接口返回结果不明确
- 不能直接在线测试接口,通常需要使用工具,比如postman
- 接口文档太多,不好管理
Swagger也就是为了解决这个问题,当然也不能说Swagger就一定是完美的,当然也有缺点,最明显的就是代码移入性比较强。
这里讲解的是SpringBoot整合Swagger2,直接生成接口文档的方式。
一、依赖
1 <!-- swagger2 start--> 2 <dependency> 3 <groupId>io.springfox</groupId> 4 <artifactId>springfox-swagger2</artifactId> 5 <version>2.6.1</version> 6 </dependency> 7 <dependency> 8 <groupId>io.springfox</groupId> 9 <artifactId>springfox-swagger-ui</artifactId> 10 <version>2.6.1</version> 11 </dependency> 12 <!--swagger-ui-layer--> 13 <dependency> 14 <groupId>com.github.xiaoymin</groupId> 15 <artifactId>swagger-bootstrap-ui</artifactId> 16 <version>1.9.1</version> 17 </dependency> 18 <!-- swagger2 end-->
二、Swagger配置类
特别要注意的是里面配置了api文件也就是controller包的路径,不然生成的文档扫描不到接口。
1 import io.swagger.annotations.ApiOperation; 2 3 import org.springframework.context.annotation.Bean; 4 import org.springframework.context.annotation.Configuration; 5 6 import springfox.documentation.builders.ApiInfoBuilder; 7 import springfox.documentation.builders.PathSelectors; 8 import springfox.documentation.builders.RequestHandlerSelectors; 9 import springfox.documentation.service.ApiInfo; 10 import springfox.documentation.spi.DocumentationType; 11 import springfox.documentation.spring.web.plugins.Docket; 12 import springfox.documentation.service.Tag; 13 14 /** 15 * @author Swgger2 16 * @ClassName Swgger2 17 * @Description 18 * @date 2017-07-10 22:12:31 19 */ 20 @Configuration 21 public class Swagger2 { 22 23 @Bean 24 public Docket createRestApi() { 25 return new Docket(DocumentationType.SWAGGER_2) 26 .apiInfo(apiInfo()) 27 .tags(new Tag("order", "订单模块"),getTags()) 28 .select() 29 .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class)) 30 .paths(PathSelectors.any()) 31 .build(); 32 } 33 34 private ApiInfo apiInfo() { 35 return new ApiInfoBuilder() 36 .title("springboot利用swagger构建api文档") 37 .description("简单优雅的restfun风格,http://127.0.0.1:8080/myweb/swagger-ui.html") 38 .termsOfServiceUrl("http://127.0.0.1:8080/myweb/swagger-ui.html") 39 .version("1.0") 40 .build(); 41 } 42 43 private Tag[] getTags() { 44 Tag[] tags = { 45 new Tag("address", "地址"),new Tag("customer", "商户") 46 }; 47 return tags; 48 } 49 }
三、开启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
http://127.0.0.1:8080/app/doc.html
四、常规用法
头部展示方法:
@Controller
@RequestMapping("order")
@Api(tags={"order"})
public class orderController {
}
示例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:多个请求参数