在 Spring Boot 项目中使用 Knife4J 生成接口 API 文档

前言

API 文档是现代软件开发中不可或缺的一部分,它能够帮助开发者了解应用程序的各个接口是如何工作的。在众多 API 文档工具中,Swagger 是最流行的一个,而 Knife4J 则是基于 Swagger 2 构建的一个强大的 UI 层,提供了更丰富的功能和更好的用户体验。

本篇文章将详细介绍如何在 Spring Boot 项目中集成 Knife4J,并生成高质量的 API 文档。

准备环境

为了确保一切顺利,我们需要确认以下条件已满足:

  • 已安装 JDK 1.8 或更高版本。
  • 已安装 Maven 或 Gradle。
  • 已有一个基本的 Spring Boot 项目。

步骤一:添加依赖

pom.xml 文件中添加必要的依赖。确保你已经添加了 Swagger 2 的依赖,因为 Knife4J 是基于 Swagger 2 的。

<!-- 添加 Swagger 2 的依赖 -->
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger2</artifactId>
    <version>2.9.2</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.9.2</version>
</dependency>

<!-- 添加 Knife4J 的依赖 -->
<dependency>
    <groupId>com.github.xiaoymin</groupId>
    <artifactId>knife4j-spring-boot-starter</artifactId>
    <version>2.0.4</version> <!-- 请使用最新的版本 -->
</dependency>

步骤二:配置 Swagger

接下来需要配置 Swagger,以便它可以扫描你的控制器并生成 API 文档。这可以通过创建一个新的 Java 配置类来实现。

import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableSwagger2
public class SwaggerConfig {

    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                .apis(RequestHandlerSelectors.basePackage("your.package.controller")) // 指定要扫描的控制器包
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Spring Boot 使用 Knife4J 生成 API 文档示例")
                .description("这是一个使用 Spring Boot 和 Knife4J 自动生成 API 文档的示例项目")
                .version("1.0")
                .build();
    }
}

注意事项

  • 替换 "your.package.controller" 为你的实际 Controller 包路径。
  • 如果你的应用中有多个不同的模块,可以考虑使用多个 Docket 实例,每个实例对应一个模块。

步骤三:自定义文档

虽然默认情况下 Swagger 与 Knife4J 就能很好地工作,但你还可以进一步自定义文档,使其更符合你的需求。

自定义全局参数

@Bean
public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("your.package.controller"))
            .paths(PathSelectors.any())
            .build()
            .globalOperationParameters(parameters()); // 添加全局参数
}

private List<Parameter> parameters() {
    ParameterBuilder tokenPar = new ParameterBuilder();
    List<Parameter> pars = new ArrayList<>();
    tokenPar.name("Authorization").description("令牌").modelRef(new ModelRef("string"))
            .parameterType("header").required(false).build();
    pars.add(tokenPar.build());
    return pars;
}

忽略特定的 Controller 或者 Method

@Bean
public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("your.package.controller"))
            .apis(RequestHandlerSelectors.not(RequestHandlerSelectors.basePackage("your.package.ignore"))) // 忽略指定的包
            .paths(PathSelectors.any())
            .build();
}

自定义响应消息

@Bean
public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("your.package.controller"))
            .paths(PathSelectors.any())
            .build()
            .useDefaultResponseMessages(false) // 不使用默认的响应消息
            .globalResponseMessage(RequestMethod.GET, newArrayList(
                    new ResponseMessageBuilder().code(401).message("未授权").build(),
                    new ResponseMessageBuilder().code(403).message("禁止访问").build(),
                    new ResponseMessageBuilder().code(404).message("找不到资源").build()));
}

自定义安全方案

@Bean
public Docket createRestApi() {
    SecurityScheme apiKey = new ApiKey("apiKey", "Authorization", "header");
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .securitySchemes(Arrays.asList(apiKey))
            .securityContexts(Arrays.asList(securityContext()))
            .select()
            .apis(RequestHandlerSelectors.basePackage("your.package.controller"))
            .paths(PathSelectors.any())
            .build();
}

private SecurityContext securityContext() {
    return SecurityContext.builder()
            .securityReferences(defaultAuth())
            .forPaths(PathSelectors.regex("/anyPath.*"))
            .build();
}

List<SecurityReference> defaultAuth() {
    AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
    AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
    authorizationScopes[0] = authorizationScope;
    return Arrays.asList(new SecurityReference("apiKey", authorizationScopes));
}

步骤四:测试 Knife4J

启动你的 Spring Boot 项目后,访问以下 URL 来查看 Knife4J 文档页面:

http://localhost:8080/doc.html

Knife4J 默认会覆盖 Swagger UI 的界面,所以不需要额外的配置。如果你想要同时启用 Swagger UI 和 Knife4J UI,可以通过以下方式配置:

@Bean
public Docket docketForSwaggerUi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .groupName("swagger") // 设置 Swagger UI 的分组名称
            .enable(true) // 是否启用 Swagger UI
            .select()
            .apis(RequestHandlerSelectors.basePackage("your.package.controller"))
            .paths(PathSelectors.any())
            .build();
}

这样你就可以同时访问 Swagger UI(http://localhost:8080/swagger-ui.html)和 Knife4J UI(http://localhost:8080/doc.html)。

步骤五:定制样式

Knife4J 提供了一些自定义样式的方法,比如你可以更改主题颜色,或者修改文档的标题等。这些都可以通过配置类中的 Docket 配置来完成。

@Bean
public Docket createRestApi() {
    return new Docket(DocumentationType.SWAGGER_2)
            .apiInfo(apiInfo())
            .select()
            .apis(RequestHandlerSelectors.basePackage("your.package.controller"))
            .paths(PathSelectors.any())
            .build()
            .groupName("group1") // 分组名称
            .pathMapping("/") // 路径映射
            .apiInfo(apiInfo());
}

private ApiInfo apiInfo() {
    return new ApiInfoBuilder()
            .title("Spring Boot 使用 Knife4J 生成 API 文档示例")
            .description("这是一个使用 Spring Boot 和 Knife4J 自动生成 API 文档的示例项目")
            .version("1.0")
            .termsOfServiceUrl("http://example.com/terms")
            .contact(new Contact("Your Name", "http://example.com", "your.email@example.com"))
            .license("Apache License Version 2.0")
            .licenseUrl("https://www.apache.org/licenses/LICENSE-2.0")
            .build();
}

结语

通过上述步骤,你可以在 Spring Boot 项目中成功地集成 Knife4J,并生成高质量的 API 文档。如果你遇到了任何问题或者需要更多帮助,请随时查阅官方文档或寻求社区支持。

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值