SpringBoot整合Knife4j
2024年6月1日大约 2 分钟
介绍
Knife4j 是 springfox 3.0.0 和 springdoc-openapi 的增强。
knife4j是一个集Swagger2 和 OpenAPI3为一体的增强解决方案,帮助开发者快速聚合使用OpenAPI规范,快速生成API文档,并且提供一些额外的功能.
Spring Boot 集成 Knife4j
- 添加依赖:引入 Knife4j 包
 
在 Spring Boot 项目的pom.xml文件中添加以下依赖:
<!--  knife4j-openapi3 -->  
<dependency>  
    <groupId>com.github.xiaoymin</groupId>  
    <artifactId>knife4j-openapi3-spring-boot-starter</artifactId>  
    <version>4.4.0</version>  
</dependency>- 配置 Knife4j
 
在配置包下增加 SwaggerConfig
import io.swagger.v3.oas.models.ExternalDocumentation;  
import io.swagger.v3.oas.models.OpenAPI;  
import io.swagger.v3.oas.models.info.Info;  
import io.swagger.v3.oas.models.info.License;  
import lombok.extern.slf4j.Slf4j;  
import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  
  
@Slf4j  
@Configuration  
public class SwaggerConfig {  
    @Bean  
    public OpenAPI springShopOpenAPI() {  
        return new OpenAPI()  
                .info(new Info().title("十六进制说")  
                        .description("十六进制说API文档")  
                        .version("v1")  
                        .license(new License().name("Apache 2.0").url("http://springdoc.org")))  
                .externalDocs(new ExternalDocumentation()  
                        .description("外部文档")  
                        .url("https://springshop.wiki.github.org/docs"));  
    }  
}在application-dev.yml文件中增加:
# springdoc-openapi项目配置,访问地址:http://127.0.0.1:8080/doc.html  
springdoc:  
  swagger-ui:  
    path: /swagger-ui.html  
    tags-sorter: alpha  
    operations-sorter: alpha  
  api-docs:  
    path: /v3/api-docs  
  group-configs:  
    - group: 'default'  
      paths-to-match: '/**'  
      packages-to-scan: com.java.trigger
# knife4j的增强配置,不需要增强可以不配  
# 参考:https://doc.xiaominfo.com/docs/quick-start  
#参考:https://gitee.com/xiaoym/swagger-bootstrap-ui-demo/tree/master/knife4j-springdoc-openapi-demo  
knife4j:  
  enable: true  
  setting:  
    language: zh_cn  
    swagger-model-name: 实体类列表  
    home-custom-path:  
  documents:  
    - name: 标题1  
      locations: classpath:markdown/*  
      group: default  
    - name: 标题2  
      locations: classpath:markdown1/*  
      group: 用户模块  
  basic:  
    enable: false  
    username: catcat  
    password: lisi  
  # 自动上传OpenAPI数据源到Knife4jInsight平台中  
  # 参考文档:http://knife4j.net  
  insight:  
    enable: false  
    namespace: knife4j-demo-openapi3  
    server: http://localhost:10086  
    secret: BudeU0urM30JTQ+YPZu1GddkG8h0fMgWuYeViSO4Y7Q=  
    service-name: knife4j-demo-openapi3- 运行项目
 
在浏览器中访问http://localhost:8080/doc.html,你就能看到 Knife4j 生成的 API 文档啦!
并且你访问:http://localhost:8080/swagger-ui.html,也能查看springdoc接口文档
附件
参考: