目录
官方文档:快速开始 | Knife4j
1. 在项目入口模块pom文件导入依赖
以下代码示例使用的SpringBoot版本为2.6.3,Knife4j为4.0.0版本
<!-- knife4j(API 文档工具) -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi2-spring-boot-starter</artifactId>
<version>${knife4j.version}</version>
</dependency>
SpringBoot与Knife4j版本参考:
根据自己项目版本引入对应的Knife4j版本

2. 在项目入口模块新建Knife4j配置类
配置类其实不是必须的,但是@EnableSwagger2WebMvc注解是必须的,它代表开启接口文档,如果你不配置例如以下的信息,可以直接在启动类添加该注解,但是我建议还是配置一下,起码看起来干净。
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的,这个注解可以让我们在不同环境使用不同的配置和参数。
7.打开服务地址404解决办法
有些朋友接入swagger能成功访问,但是Knife4j接入了之后打开就404,很可能是因为你的项目使用了WebMvcConfigurer或者WebMvcConfigurationSupport
那么就需要你在使用WebMvcConfigurer或者WebMvcConfigurationSupport的配置类的addResourceHandlers方法添加以下代码
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}



2302

被折叠的 条评论
为什么被折叠?



