Swagger使用
- 引入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>
2.添加Swagger配置类
@Configuration
@EnableSwagger2
public class SwaggerConfig {
/**
* Swagger2创建该Api的基本信息
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("测试API接口RESTful APIs")
.description("spring Boot 中构建RESTful API")
.termsOfServiceUrl("")
.version("1.0")
.build();
}
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.wanfeng.controller"))
.paths(PathSelectors.any())
.build();
}
}
- 在接口上使用Swagger注解添加描述即可
Swagger常用注解如下:
@Api:用在类上,说明该类的作用。
@ApiOperation:注解来给API增加方法说明。
@ApiImplicitParams : 用在方法上包含一组参数说明。
@ApiImplicitParam:用来注解来给方法入参增加说明。
参数:
·paramType:指定参数放在哪个地方
··header:请求参数放置于Request Header,使用@RequestHeader获取
··query:请求参数放置于请求地址,使用@RequestParam获取
··path:(用于restful接口)-->请求参数的获取:@PathVariable
··body:(不常用)
··form(不常用)
·name:参数名
·dataType:参数类型
·required:参数是否必须传(true | false)
·value:说明参数的意思
·defaultValue:参数的默认值
@ApiResponses:用于表示一组响应
@ApiResponse:用在@ApiResponses中,一般用于表达一个错误的响应信息
——code:数字,例如400
——message:信息,例如"请求参数异常!"
——response:抛出异常的类
@ApiModel:描述一个Model的信息(一般用在请求参数无法使用@ApiImplicitParam注解进行描述的时候)
@ApiModelProperty:描述一个model的属性
Swagger添加basic检验
- 引入依赖
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.9.3</version>
</dependency>
- 在配置类上添加 @EnableSwaggerBootstrapUI 注解
- 在.properties配置文件中添加配置
## 是否开启Basic
swagger.basic.enable=true
## Basic认证用户名
swagger.basic.username=wanfeng
## Basic认证密码
swagger.basic.password=123456