1.pom.xml引入相关jar包。
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger2 -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/io.springfox/springfox-swagger-ui -->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.9.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.guava/guava -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>28.1-jre</version>
</dependency>
2.添加swagger2的配置类。
@Configuration
@EnableSwagger2
@ComponentScan(basePackages = { "com.xxx.controller" })//扫描的包路径
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2).apiInfo(apiInfo()).select()
.paths(PathSelectors.any()).build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("用户登录")//接口标题
.description("用户登录接口")//接口描述
.version("v1.0")//版本号
.contact(new Contact("name", "url", "email"))//联系人信息
.build();
}
}
3.Controller类里请求方法加入swagger注解
@ApiOperation(value = "用户登录",tags = {"用户管理"})
@ApiImplicitParams({ @ApiImplicitParam(name = "userName", value = "用户名", paramType = "body",required=true),
@ApiImplicitParam(name = "password", value = "密码", paramType = "body",required=true) })
@RequestMapping(value = "/login", method = RequestMethod.POST)
public RestResult<String> apiMethod(
@Valid @RequestBody LoginRequestDTO loginRequestDTO, Errors errors,
HttpServletRequest request) throws Exception {
//业务处理
return null;
}
启动Spring Boot服务并访问 http://localhost:8080/swagger-ui.html
可见如下界面:
4.swagger注解说明。
@ApiOperation:
value:接口用途(必选)
notes:备注说明(可选)
httpMethod:请求方式(可选)
response:返回参数类型(可选)
tags:接口分组名(可选)
@ApiImplicitParams:(可选,当描述多个@ApiImplicitParam时候使用)
@ApiImplicitParam:(接口入参描述;本身可选,对应子字段也全部可选)
name:参数属性名
value:参数说明
required:是否必传 true/false
paramType:请求参数的获取方式
header --> @RequestHeader
query --> @RequestParam
path --> @PathVariable
body --> @RequestBody
form --> 很少使用
dataType:参数类型
defaultValue:默认值
@Api:作用于Conntroller类上
value:字段说明
description:描述
tags:分组
@ApiIgnore: 作用于接口入参参数列表,表示swagger忽略该入参
@ApiModelProperty:作用于入参实体对象的属性上(本身可选,对应子字段也全部可选)
value:字段描述
name:属性名字
dataType:属性类型
required:是否必传
example:参数样例
hidden:隐藏
@ApiResponses:(接口返回结果;可选,当描述多个@ApiResponse时候使用)
@ApiResponse:(可选)
code:HTTP请求返回码。(必选)
message:返回信息。(必选)
response:返回类型,需使用全类名。eg:"com.xxx.dto.DemoRequestDTO.class"(可选)
5.YApi导入Swagger接口。
-
5.1 通过Swagger的url导入。
YAapi 选定项目->数据管理->数据导入,按字段项依次设置即可。
-
5.2 通过YApi的Swagger自动同步项(node-schedule 定时任务导入)。
YAapi 选定项目->设置->Swagger自动同步,按字段项依次设置即可。