java springboot 正合Knife4j框架

要将 Knife4j(之前称为 SwaggerBootstrapUi)集成到 Spring Boot 项目中。

可以按照以下步骤操作:

1、添加依赖        

        在 pom.xml 文件中添加 Knife4j 的相关依赖。确保 Spring Boot 版本与 Knife4j 支持的版本相匹配。

        这里以 Maven 为例:

<dependencies>
    <!-- Springfox Swagger 依赖 -->
    <dependency>
        <groupId>io.springfox</groupId>
        <artifactId>springfox-boot-starter</artifactId>
        <version>3.0.0</version> <!-- 根据实际需要选择版本 -->
    </dependency>
    
    <!-- Knife4j UI 依赖 -->
    <dependency>
        <groupId>com.github.xiaoymin</groupId>
        <artifactId>knife4j-spring-boot-starter</artifactId>
        <version>3.0.3</version> <!-- 请根据最新版本进行调整 -->
    </dependency>
</dependencies>

2、配置 Swagger 和 Knife4j

        在 src\main\resources 目录下创建或修改 application.yml 或 application.properties 文件,配置 Swagger 和 Knife4j。

        application.yml 示例配置:

springfox:
  documentation:
    swagger-ui:
      enabled: true
    knife4j:
      enable: true # 开启 Knife4j 增强功能

server:
  port: 8080

# 如果使用的是Spring Security,可能需要配置Swagger的访问权限
# security:
#   ignored: /swagger-ui.html**, /webjars/**

3、创建 Swagger 配置类

        可选地,可以创建一个 Swagger 配置类来定制 API 文档信息。

        以下是一个简单的示例:

import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

@Configuration
@EnableSwagger2WebMvc // 使用Swagger2
public class Knife4jConfig {

    @Bean(value = "defaultApi2")
    public Docket defaultApi2() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(new ApiInfoBuilder()
                        .title("应用名称")
                        .description("API 描述")
                        .termsOfServiceUrl("http://yourwebsite.com")
                        .contact("联系人")
                        .version("1.0")
                        .build())
                // 分组名称
                .groupName("默认")
                .select()
                // 这里指定Controller扫描包路径
                .apis(RequestHandlerSelectors.basePackage("包路径"))
                .paths(PathSelectors.any())
                .build();
    }
}

4、访问 Swagger UI

        完成上述配置后,启动 Spring Boot 应用,然后访问 http://localhost:8080/项目名/doc.html(或根据你的端口配置调整),能看到 Knife4j 增强版的 Swagger UI 界面。

  • 19
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值