一:Swagger介绍
Swagger2,它可以轻松的整合到Spring Boot中,并与Spring MVC程序配合组织出强大RESTful API文档。它既可以减少我们创建文档的工作量,也可以让我们在修改代码逻辑的同时方便的修改文档说明。
效果图如下:
二:pom.xml依赖
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.2.2</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.2.2</version>
</dependency>
三:config配置文件
@Configuration
@EnableSwagger2
public class SwaggerConfig {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.globalOperationParameters(
//构建头部参数
newArrayList(
new ParameterBuilder()
.name("X-token")
.description("Description of header")
.description("登陆的Token")
.modelRef(new ModelRef("string"))
.parameterType("header")
.required(true)
.build()
)
)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
.paths(PathSelectors.any())
.build();
}
/**
* 文档说明
* @return
*/
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("RESTful API")
.description("项目web端接口文档")
.contact( "Nicky")
.version("1.0.0")
.build();
}
}
四:拦截器资源配置
@Configuration
@EnableWebMvc
@ComponentScan("com.recruit")
public class WebAppConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/statics/**").addResourceLocations("classpath:/statics/");
registry.addResourceHandler("/swagger-ui.html*").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
}
五:接口参数
@ApiOperation(value="快速登陆系统")
@ApiImplicitParams({
@ApiImplicitParam(name = "mobile", value = "手机号", required = true, dataType = "String" ,paramType = "query"),
@ApiImplicitParam(name = "verifyCode", value = "验证码", required = true, dataType = "String",paramType = "query")
})
@PostMapping("/fastEntry")
@RestInfo(auth = RestInfo.Auth.FREE_PASS)
public RespDTO fastEntry( String mobile,String verifyCode) {
logger.info("/seeker/fastEntry,mobile:{},verifyCode:{}", mobile,verifyCode);
try {
return RespDTO.success();
}catch (Exception e) {
logger.error("/seeker/fastEntry fail,", e);
return RespDTO.fail(Constants.NET_BUSY_ERROR_INFO);
}
}
⚠️注解说明:
@Api()用于类;
表示标识这个类是swagger的资源
- @ApiOperation()用于方法;
表示一个http请求的操作
value用于方法描述
notes用于提示内容
tags可以重新分组
- @ApiParam()用于方法,参数,字段说明;
表示对参数的添加元数据(说明或是否必填等)
- @ApiModel()用于类
表示对类进行说明,用于参数用实体类接收
value–表示对象名
description–描述
都可省略
- @ApiModelProperty()用于方法,字段
表示对model属性的说明或者数据操作更改
value–字段说明
name–重写属性名字
dataType–重写属性类型
required–是否必填
example–举例说明
hidden–隐藏
- @ApiIgnore()用于类,方法,方法参数
表示这个方法或者类被忽略
- @ApiImplicitParam() 用于方法
表示单独的请求参数
name–参数名
value–参数说明
required–是否必填
dataType-数据类型
paramType-参数类型
- @ApiImplicitParams() 用于方法,包含多个 @ApiImplicitParam
六:页面案例
页面文档地址:
http://localhost:8090/swagger-ui.html