Swagger2是一個開源軟件框架,由大型工具生態系統支持,可幫助開發人員設計,構建,記錄和使用Restful Web服務。
這是“維基百科”上對於Swagger2的一個介紹,可見Swagger2是屬於第三方框架,對標的是Restful風格的API,使用Swagger2生成API文檔,避免了傳統手工記錄的繁瑣,也便於保存、整理、查閱和調試API接口。
在SpringBoot項目中引入Swagger2:
- pom.xml引入對應的依賴
<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>
- 增加SwaggerConfig.java配置文件,在Applcation.java中添加@EnableSwagger2,項目啓動時同時加載swagger2
@Configuration
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
//加了ApiOperation註解的類,生成接口文檔
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
//接口對應包下的類,生成API文檔
.apis(RequestHandlerSelectors.basePackage("io.swagger.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("可讀小說")
.description("後臺管理系統API文檔")
.termsOfServiceUrl("https://swagger.io/")
.version("1.0.1")
.build();
}
}
同時利用Swagger2提供的註解對接口進行說明,通過訪問http://localhost:8080/swagger-ui.html便可獲取到相關API文檔。
註解的使用(demo)
@Api(tags="小說信息接口")
@RestController
@RequestMapping("/info")
public class InfoController {
@ApiOperation("添加小說信息")
@PutMapping("/add")
private String addInfo(){
return "success";
}
@ApiOperation("獲取小說信息")
@GetMapping("/{id}")
private String getInfo( @ApiParam("小說id") @PathVariable("id")int id){
return "info" + id;
}
}
最後再說說Swagger2的常用註解:
- @Api:用於類,表示標識這個類是swagger的資源
- @ApiOperation:用於方法,表示一個http請求的操作
- @ApiParam:用於方法,參數,字段說明,表示對參數的添加元數據(說明或是否必填等)
- @ApiModel:用於類,表示對數據模型進行說明,用於參數用實體類接收
- @ApiModelProperty:用於方法,字段,表示對model屬性的說明
- @ApiIgnore:用於類,方法,方法參數,對應的將不會被顯示到文檔裏
- @ApiImplicitParam:用於方法,作用於非對象參數集
- @ApiImplicitParams:用於方法,包含多個 @ApiImplicitParam