1.主要依賴
<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>
2.主要配置類
- 添加swaggerEnabled屬性可以通過spring-boot的配置文件實現不同環境是否打開swagger
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Value("${swagger.enabled}")
Boolean swaggerEnabled;
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.enable(swaggerEnabled)
.select()
.apis(RequestHandlerSelectors.basePackage("com.mk.lime.admin.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("swagger-title")
.description("swagger-description")
.contact(new Contact("name", "url", "email"))
.version("1.0.0")
.build();
}
}
3.Swagge及代碼
- 添加swagger的相關注解
- 啓動項目,訪問swagger地址,默認端口8080,可通過spring-boot配置文件修改端口
地址:http://localhost:8080/swagger-ui.html#/
4.常用Swagger註解
位於io.swagger.annotations包下,僅列出常見的幾個註解
註解 | 常用途 |
---|---|
@Api | Controller類說明 |
@ApiModel | Model類說明 |
@ApiModelProperty | Model類屬性說明 |
@ApiOperation | Controller類方法說明 |
@ApiParam | Controller類方法請求參數說明 |
@ApiResponses @ApiResponse | Controller類方法返回說明 |