Swagger-自动生成接口文档
Swagger
Swagger3是接口文档生成工具
依赖 pom.xml
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi2-spring-boot-starter</artifactId>
<version>4.4.0</version>
</dependency>
配置文件 application.yml
server:
port: 8080
servlet:
context-path: /api # 如果填写接口文档地址则为api/doc.html
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/library-management?serverTimezone=GMT%2b8
username: root
password: 123456
# 支持 swagger3 静态资源映射
mvc:
pathmatch:
matching-strategy: ant_path_matcher
# 接口文档配置
knife4j:
enable: true
openapi:
title: "接口文档"
version: 1.0
group:
default:
api-rule: package
api-rule-resources:
- com.example.springboot.controller # 写自己的包
然后我们启动项目
http://localhost:8080/api/doc.html#/home (我的接口文档地址)
打开后就能看到接口文档页面
http://localhost:8080/api/v2/api-docs (这里可以看到Swagger源码)
如果你的项目中引入三方ui依赖,knife4j,访问doc.html遇到问题。
1、可能是因为当前环境拦截了 Swagger 默认的静态资源,只需在配置类文件中实现 WebMvcConfigurer 接口并重写 addResourceHandlers 方法即可。
@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
log.info("开始资源放行");
registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
super.addResourceHandlers(registry);
}
}