Swagger-自动生成接口文档

Swagger

官网:https://swagger.io/

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);
    }
}
posted @   韩续贤  阅读(154)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示