Swagger 是一款RESTFUL接口的文檔線上自動生成+功能測試功能軟體
前後端分離的時候swagger可以減輕後端人員的文檔編寫的工作量;下面簡單講一下springboot內建swagger的過程以及用法;
首先maven引入swagger的依賴
<!-- Swagger -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.7.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.7.0</version>
</dependency>
swagger的配置,如下javaconfig
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.xx.xxx"))
.paths(PathSelectors.any())
.build()
.useDefaultResponseMessages(false)
.enableUrlTemplating(false);
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("xxxxxxxxxxxxx接口")
.description("xxxxxx的詳細說明")
.contact(new Contact("hym","https://xxx.xxxxxx.com.cn","[email protected]"))
.version("1.0")
.build();
}
}
@Configuration
public class WebJarsConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
完成好上面的配置之後,我們通路http://ipaddress:port/swagger-ui.html即可
下面借鑒一下swagger的注解的含義,如下
一、相關注解解讀
1. @Api
用在類上,說明該類的作用
@Api(value = "xxxxxxxx", description = "使用者相關api")
2. @ApiOperation
用在方法上,說明方法的作用
@ApiOperation(value = "查找使用者", notes = "查找使用者", httpMethod = "GET", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
3 @ApiImplicitParams
用在方法上包含一組參數說明
4. @ApiImplicitParam
用在@ApiImplicitParams注解中,指定一個請求參數的各個方面
paramType:參數放在哪個地方
header–>請求參數的擷取:@RequestHeader
query–>請求參數的擷取:@RequestParam
path(用于restful接口)–>請求參數的擷取:@PathVariable
body(不常用)
form(不常用)
name:參數名
dataType:參數類型
required:參數是否必須傳
value:參數的意思
defaultValue:參數的預設值
@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "唯一id", required = true, dataType = "Long", paramType = "path"), })
5. @ApiResponses
用于表示一組響應
6. @ApiResponse
用在@ApiResponses中,一般用于表達一個錯誤的響應資訊
code:數字,例如400
message:資訊,例如”請求參數沒填好”
response:抛出異常的類
@ApiResponses(value = {
@ApiResponse(code = 404, message = "No Name Provided")
})
7. @ApiModel
描述一個Model的資訊(這種一般用在post建立的時候,使用@RequestBody這樣的場景,請求參數無法使用@ApiImplicitParam注解進行描述的時候)
@ApiModel(value = "xxxxx")
8. @ApiModelProperty
描述一個model的屬性
@ApiModelProperty(value = "xxxxxxx")