1. 在项目入口模块pom文件导入依赖
            <!-- knife4j(API 文档工具) -->
            <dependency>
                <groupId>com.github.xiaoymin</groupId>
                <artifactId>knife4j-openapi2-spring-boot-starter</artifactId>
                <version>${knife4j.version}</version>
            </dependency>2. 在项目入口模块新建Knife4j配置类
配置类其实不是必须的,但是@EnableSwagger2WebMvc注解是必须的,它代表开启接口文档,如果你不配置例如以下的信息,可以直接在启动类添加该注解,但是我建议还是配置一下,起码看起来干净。
            
            
              java
              
              
            
          
          import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Contact;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;
/**
 * @Author: Desmond
 * @CreateTime: 2024-08-02
 * @Description: Knife4j配置类
 */
@Configuration
@EnableSwagger2WebMvc
public class Knife4jConfig {
    @Bean("webApi")
    public Docket createApiDoc() {
        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(buildApiInfo())
                // 分组名称
                .groupName("Web 前台接口")
                .select()
                // 这里指定 Controller 扫描包路径
                .apis(RequestHandlerSelectors.basePackage("com.desmond.web.controller"))
                .paths(PathSelectors.any())
                .build();
        return docket;
    }
    /**
     * 构建 API 信息
     * @return
     */
    private ApiInfo buildApiInfo() {
        return new ApiInfoBuilder()
                .title("xxx接口文档") // 标题
                .description("xxx是一款由 Spring Boot + Vue 3.2 开发的前后端分离项目") // 描述
                .termsOfServiceUrl("www.xxx.com") // API 服务条款
                .contact(new Contact("Desmond", "www.xxx.com", "xxx@.com")) // 联系人
                .version("1.0") // 版本号
                .build();
    }3. 启动项目

如果控制台出现以上日志,说明配置成功
默认路径:http://localhost:8080/doc.html
如果你项目路径不一样,自行修改拼接/doc.html即可

页面展示如上,我个人认为比swagger2使用还更简单
4. 常用的几个注解
@Api 作用于controller
@ApiOperation 作用于接口

效果如下

@ApiOperation 的 notes参数还可以给接口进行注释


@ApiModel 作用于实体类
@ApiModelProperty 作用于类属性

5. 调试

点击发送即可对接口进行请求,如果你对响应类也写了相关注解,页面也会有相应的注释



6. 只在开发环境生效

可以在配置类使用@Profile("dev") ,这样Knife4j接口文档就只会在dev环境被计划
这个注解是SpringBoot的,这个注解可以让我们在不同环境使用不同的配置和参数。