1 简介
Knife4j是一个集Swagger2 和 OpenAPI3为一体的增强解决方案
由于springfox长久未更新,并且Swagger2规范在目前来看,一定程度上也并未升级,规范已经全部往OpenAPI3规范靠拢,因此,在Spring Boot 3.x版本中,开发者应该选择OpenAPI3规范来作为应用框架的开发首选方案。
Knife4j官方网站
2 版本对应关系
boot 版本 | Knife4j Swagger2规范 | Knife4j OpenAPI3规范 |
---|---|---|
1.5.x~2.0.0 | <Knife4j 2.0.0 | >=Knife4j 4.0.0 |
2.0~2.2 | Knife4j 2.0.0 ~ 2.0.6 | >=Knife4j 4.0.0 |
2.2.x~2.4.0 | Knife4j 2.0.6 ~ 2.0.9 | >=Knife4j 4.0.0 |
2.4.0~2.7.x | >=Knife4j 4.0.0 | >=Knife4j 4.0.0 |
>= 3.0 | >=Knife4j 4.0.0 | >=Knife4j 4.0.0 |
3 项目示例
3.1 配置pom文件
3.2 boot版本
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.2.1</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
3.3 引入Knife4j
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>4.5.0</version>
</dependency>
3.4 配置 application.yml
# springdoc-openapi项目配置
springdoc:
swagger-ui:
path: /swagger-ui.html
tags-sorter: alpha
operations-sorter: alpha
api-docs:
path: /v3/api-docs
完成上面配置后启动项目,输入网址localhost:8080/doc.html
就可以看到默认配置页面
3.5 自定义配置
@Slf4j
@Component
public class SwaggerConfig {
// 分成多个模块,默认只有default分组
@Bean
public GroupedOpenApi userApi(){
String[] paths = { "/**" };
String[] packagedToMatch = { "com.leis.bear.controller" };
return GroupedOpenApi.builder().group("用户模块")
.pathsToMatch(paths)
.addOperationCustomizer((operation, handlerMethod) -> {
return operation.addParametersItem(new HeaderParameter().name("groupCode").example("测试").description("集团code").schema(new StringSchema()._default("BR").name("groupCode").description("集团code")));
})
.packagesToScan(packagedToMatch).build();
}
// 首页描述信息
@Bean
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("XXX用户系统API")
.version("1.0")
.description( "Knife4j集成springdoc-openapi示例")
.termsOfService("http://asdasdasdas.com")
.license(new License().name("Apache 4.0")
.url("http://doc.xiaominfo.com"))
).addSecurityItem(new SecurityRequirement().addList(HttpHeaders.AUTHORIZATION))
.components(new Components().addSecuritySchemes(HttpHeaders.AUTHORIZATION,new SecurityScheme()
.name(HttpHeaders.AUTHORIZATION).type(SecurityScheme.Type.HTTP).scheme("bearer")));
}
}
3.6 页面信息
在左上角选择分组信息,请求地址http://localhost:8080/doc.html
。
Swagger页面请求地址`http://localhost:8080/swagger-ui/index.html#/](https://i-blog.csdnimg.cn/direct/5e33f3e2947a43049a1d06f1dcc5a8a5.png)
4 注解信息
4.1 2 和 3的注解对应
@Api
→@Tag
@ApiIgnore
→@Parameter(hidden = true)
或者@Parameter(hidden = true)
或者@Hidden
@ApiImplicitParam
→@Parameter
@ApiImplicitParams
→@Parameters
@ApiModel
→@Schema
@ApiModelProperty(hidden = true)
→@Schema(accessMode = READ_ONLY)
@ApiModelProperty
→@Schema
@ApiOperation(value = "foo", notes = "bar")
→@Operation(summary = "foo", description = "bar")
@ApiParam
→@Parameter
@ApiResponse(code = 404, message = "foo")
→@ApiResponse(responseCode = "404", description = "foo")