knife4j是为Java MVC框架集成Swagger生成Api文档的增强解决方案,前身是swagger-bootstrap-ui,取名kni4j是希望它能像一把匕首一样小巧,轻量,并且功能强悍!
官网地址:
Knife4j · 集Swagger2及OpenAPI3为一体的增强解决方案. | Knife4j
本文以Springboot3+版本集成knife4j叙述(请注意版本差别,不同版本写法不同)。
第一步:创建Spring Boot项目并且在pom.xml中引入Knife4j的依赖包,代码如下:
XML
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-spring-web</artifactId>
<version>3.0.0</version>
</dependency>
第二步:创建Swagger配置依赖,代码如下:
java
package blog.web.config;
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.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
@Configuration
public class Knife4jConfiguration {
@Bean
public Docket docketAdmin() {
System.out.println("swagger 准备生成接口文档...");
ApiInfo apiInfo = new ApiInfoBuilder()
.title("清山博客文档")
.version("2.0")
.description("清山博客项目接口文档")
.build();
return new Docket(DocumentationType.SWAGGER_2)
.groupName("管理端接口")
.apiInfo(apiInfo)
.select()
// 指定swagger需要扫描的包
.apis(RequestHandlerSelectors.basePackage("blog.web"))
.paths(PathSelectors.any())
.build();
}
}
第三步:新建一个接口Controller类,如下:
java
@RestController
@RequestMapping("body")
@Tag(name = "body参数")
public class BodyController {
@Operation(summary = "普通body请求")
@PostMapping("/body")
public ResponseEntity<FileResp> body(@RequestBody FileResp fileResp){
return ResponseEntity.ok(fileResp);
}
@Operation(summary = "普通body请求+Param+Header+Path")
@Parameters({
@Parameter(name = "id",description = "文件id",in = ParameterIn.PATH),
@Parameter(name = "token",description = "请求token",required = true,in = ParameterIn.HEADER),
@Parameter(name = "name",description = "文件名称",required = true,in=ParameterIn.QUERY)
})
@PostMapping("/bodyParamHeaderPath/{id}")
public ResponseEntity<FileResp> bodyParamHeaderPath(@PathVariable("id") String id,@RequestHeader("token") String token, @RequestParam("name")String name,@RequestBody FileResp fileResp){
fileResp.setName(fileResp.getName()+",receiveName:"+name+",token:"+token+",pathID:"+id);
return ResponseEntity.ok(fileResp);
}
}
注意事项:
1.Spring Boot 3 只支持OpenAPI3规范
2.Knife4j提供的starter已经引用springdoc-openapi的jar,开发者需注意避免jar包冲突
3.JDK版本必须 >= 17
参考: