Swagger2 常用使用 及 SpringBoo 整合 Swagger2

Posted 花谢^花开

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Swagger2 常用使用 及 SpringBoo 整合 Swagger2相关的知识,希望对你有一定的参考价值。

手写Api文档的几个痛点:

  1. 文档需要更新的时候,需要再次发送一份给前端,也就是文档更新交流不及时。
  2. 接口返回结果不明确
  3. 不能直接在线测试接口,通常需要使用工具,比如postman
  4. 接口文档太多,不好管理

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(@ApiParam @RequestBody 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 = "订单号")
  private String orderNo;
  @ApiModelProperty(value = "收货人名称")
  private String consigneeName;
  @ApiModelProperty(value = "收货人手机号")
  private String consigneePhone;
  @ApiModelProperty(value = "收货地址所在区域+详细地址")
  private String adress;
  .........

}

 

































































































以上是关于Swagger2 常用使用 及 SpringBoo 整合 Swagger2的主要内容,如果未能解决你的问题,请参考以下文章

spring boot 1.5.4 集成Swagger2构建Restful API(十八)

Swagger2 常用注解使用及其说明

Swagger2 常用注解使用及其说明

SpringBoot项目中使用Swagger2及注解解释(详细)

swagger2 常用注解说明

swagger2常用注解说明