1.swagger,可以這么理解swagger是接口規范。Rest Api 傳遞參數的除了get請求外,put post,需要傳遞json。或者就是直接都通過傳遞json到后台
這里主要介紹一下springboot后台整合swagger的使用步驟。如果要查看swagger(OpenApi)的規范,可以參考git的官方文件規范。
springboot 整合swagger的簡單基本使用。
第一步:
在pom.xml文件中引入依賴:
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
第二步:
添加swagger的配置類
@Configuration
@EnableSwagger2
@ComponentScan(basePackages = { "com.xxx.controller" })//掃描的包路徑
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
.paths(PathSelectors.any()).build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("用戶登錄")//接口標題
.description("用戶登錄接口")//接口描述
.version("v1.0")//版本號
.contact(new Contact("name", "url", "email"))//聯系人信息
.build();
}
}
如果沒有添加@ComponentScan(basePackages={})掃描的包路徑。也可以通過一下方式實現添加多個掃描包
@Configuration
@EnableSwagger2
public class SwaggerConfiguration {
private static final String SPLITOR = ",";
//重寫basePackage()支持多包掃描
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(basePackage("cn.com.agree.aweb.controller.gateway" + SPLITOR
+ "cn.com.agree.aweb.controller.cluster" + SPLITOR
+ "cn.com.agree.aweb.controller.flow" + SPLITOR
+ "cn.com.agree.aweb.controller.fuse" + SPLITOR
+ "cn.com.agree.aweb.controller.conversion" + SPLITOR
+ "cn.com.agree.aweb.controller.signature" + SPLITOR
+ "cn.com.agree.aweb.controller.api"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("網關管控接口")
// .description("更多請關注http://www.baidu.com")
// .termsOfServiceUrl("http://www.baidu.com")
// .contact("sunf")
.version("v1.1")
.build();
}
}
第三步則是在Controller類里加入swagger注解,這樣對應的接口可以在項目啟動后通過url路徑(http://localhost:8080/swagger-ui.html)訪問到。
@ApiOperation(value = "用戶登錄",tags = {"用戶管理"})
@ApiImplicitParams({ @ApiImplicitParam(name = "userName", value = "用戶名", paramType = "body",required=true),
@ApiImplicitParam(name = "password", value = "密碼", paramType = "body",required=true) })
@RequestMapping(value = "/login", method = RequestMethod.POST)
public RestResult<String> apiMethod(
@Valid @RequestBody LoginRequestDTO loginRequestDTO, Errors errors,
HttpServletRequest request) throws Exception {
//業務處理
return null;
}
請求參數在路徑上的注解PathVariable使用,示例如下:
@ApiOperation("根據id刪除后端服務")
@DeleteMapping("/v1.1/{id}")
@ApiImplicitParam(name = "id", value = "后端服務id", paramType = "path", dataType = "string", required = true)
@OperationLog(name = "刪除后端服務")
public Object deleteServerById(@PathVariable("id") String id, @RequestParam("api_id") String apiId) {
return apiServiceService.deleteServerById(id, apiId);
}
以上三步驟就是簡單的swagger基本使用步驟。
訪問swaggerUi后,頁面如下:點開對應的接口,可以直接在瀏覽器進行測試接口是否可用。

