- 添加依賴
pom.xml
<!--JSON API文檔的生成-->
<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>
- 創(chuàng)建swagger配置文件
SwaggerConfig.java
@Configuration
@EnableSwagger2
@ConditionalOnExpression("${swagger.enable:true}")
public class SwaggerConfig {
@Bean
public Docket swaggerSpringMvcPlugin(){
ApiInfo apiInfo = new ApiInfoBuilder()
.title("** APIs")
.description("**的接口文檔")
.version("1.0.0")
.termsOfServiceUrl(null)
.contact(new Contact("name", "url", "email"))
.license("作者:**")
.licenseUrl("http://")
.build();
Docket docket = new Docket(DocumentationType.SWAGGER_2)
.select()
//.paths(regex("/api/*")) // 指定接口url
.paths(PathSelectors.any())
.build()
.apiInfo(apiInfo)
.useDefaultResponseMessages(false);
return docket;
}
}
- 配置具體的接口注釋數(shù)據(jù)的簡單示例,更多的注釋可參看官網(wǎng)
- @Api() 用于controller類
- @ApiOperation()用于controller的方法
ApiOperation(value = "/api/edit", notes = "", httpMethod = "POST", response = Response.class)
- @ApiResponses用于controller的方法版扩,響應(yīng)的數(shù)據(jù)
@ApiResponses({
@ApiResponse(code = 100 , message = "請(qǐng)選擇部門"),
@ApiResponse(code = 101, message = "請(qǐng)選擇日期")
})
- @ApiImplicitParams()用于controller的方法习勤,參數(shù)注釋
@ApiImplicitParams({
@ApiImplicitParam(name = "department", value = "部門", required = true, paramType = "form"),
@ApiImplicitParam(name = "date", value = "日期", required = true, paramType = "form")
})
name 參數(shù)
value 參數(shù)的描述
required 是否必傳
paramType 參數(shù)存放位置:header樊展、query报亩、path(resuful接口)卷员、body、form
dataType 參數(shù)類型
defaultValue 參數(shù)默認(rèn)值
- @ApiModel() 用于bean對(duì)象的類
@ApiModel(value = "", description = "")
- @ApiModelProperty()(用于bean對(duì)象的方法
@ApiModelProperty(value = "", name="")
value–字段說明
name–重寫屬性名字
dataType–重寫屬性類型
required–是否必填
example–舉例說明
hidden–隱藏
- @ApiParam()具體請(qǐng)求參數(shù)
@ApiParam(name = "", value = "", required = true)
name 參數(shù)
value 參數(shù)簡單描述
defaultValue 描述參數(shù)默認(rèn)值
allowableValues 可接收參數(shù)值限制
required 是否為必傳參數(shù)
- 與spring security配合
使用了spring security時(shí)居砖,需要登錄訪問,或者在security配置文件中添加對(duì)url的忽略驴娃。
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(
"/swagger-ui.html",
"/webjars/**",
"/v2/api-docs",
"/swagger-resources",
"/swagger-resources/configuration/ui",
"/swagger-resources/configuration/security"
);
}
}
5.訪問 ip:port/swagger-ui.html
- 控制swagger關(guān)閉和啟動(dòng)
SwaggerConfig.java
中添加注釋@ConditionalOnExpression("${swagger.enable:true}")
application.properties
更改:true
啟動(dòng)奏候,false
關(guān)閉,線上系統(tǒng)需要關(guān)閉唇敞。