1. 程式人生 > >Swagger2 常用使用 及 SpringBoo 整合 Swagger2

Swagger2 常用使用 及 SpringBoo 整合 Swagger2

ttr ext 路徑 bool base64 catch swa frame tac

手寫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