依赖
- swagger
- knife4j:https://doc.xiaominfo.com/docs/quick-start
这两个是用于生成api文档网页的,其中knife4j是swagger的增强ui版,通过注解的方式使用,不用写其他代码
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
<version>3.0.3</version>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<version>1.6.5</version>
<scope>compile</scope>
</dependency>
Controller层
Controller类注解
@Api(value=“Redis”, tags=“”[Car]")
其中value是对该controller下api的描述信息,tags是分类标签,相同tag的api会放在一起展示
@ApiSort(64)
是对api展示顺序的排序,传入的值越小该controller下的api就排在越前面
@ApiVersion(“v1”)
会修改路由,如原RequestMapping指定的路由为/create,加上该注解后请求路由变为/v12/create,用于区别不同版本的api
Controller方法注解
@ApiOperation(“publish message”)
@ApiOperation(value=“publish message”, note=“publish message”)
value为接口简短介绍,note为长说明,note在文档中显示为标题名
@ApiOperationSupport(ignoreParameters = {“id”})
对于添加实体等接口,自动生成id等字段的,可以不需要前端传入id,则配置ignoreParameters让id不会出现在api文档中。
该注解有以下参数:
- order: 表示方法在页面中显示的排序位置,默认值为0。(原swagger的ApiSort注解不能注解方法)
- ignoreParameters: 忽略测试参数
- author: 方法的作者(原swagger的Api注解不能注解方法)
- group: 方法所属的分组
@ApiResponses
@ApiResponses(value = {
@ApiResponse(code = 200, message = "成功", response = String.class),
@ApiResponse(code = 404, message = "channel不存在"),
@ApiResponse(code = 500, message = "服务器内部错误")
})
在文档里对返回的状态码进行说明(不设置也有几个常见的状态码)
实体层
实体类注解
@ApiModel(value = “User”, description = “用户实体对象”)
value是名字,description是描述
实体属性注解
@ApiModelProperty(value = “用户id”, required = true)
这样在接口文档中,涉及到Car的接口的id项会有required = true的说明
生成文档和其他功能
spring启动后访问http://localhost:8080/doc.html ,可以查看网页版api文档,在配置中开启knife4j.enable=true,可以使用knife4j提供的增强功能:
- 导出文档的md、word、html、openapi版
- 可直接复制接口到postman
- 可设置全局参数,比如修改全局请求header
- 接口排序,自定文档的展示顺序
- 配合 Spring Security 可以实现对 API 文档的访问控制
以下是生成的md和word文件:
https://shimo.im/file/5xkGogOBaaH2dnkX/
https://shimo.im/file/gO3odzVBzgCxxNqD/
其他配置
由于不配置会默认生成所有的接口,包括spring自带的error相关接口和entity自动生成的接口,这些一般不需要出现在接口文档中,因此配置如下,这样将只会扫描com.example.demo.controller包中的接口。
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
public class SwaggerConfig {
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
// 指定Swagger扫描的包路径
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build();
}
}
此外还可以指定仅生成特定路由前缀的文档,如下为仅扫描以“/api”开头的接口:
@Bean
public Docket api() {
return new Docket(DocumentationType.SWAGGER_2)
.select()
.apis(RequestHandlerSelectors.any())
.paths(PathSelectors.ant("/api/**"))
.build();
}