springboot3 集成 knif4j :
访问地址:
swagger
接口文档默认地址:http://localhost:8080/swagger-ui.html#
Knife4j
接口文档默认地址:http://127.0.0.1:8080/doc.html
Maven:
xml
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>4.4.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-gateway-spring-boot-starter</artifactId>
<version>${knife4j-openapi3.version}</version>
</dependency>
基础微服务配置:
yml
knife4j:
# 开启增强配置
enable: true
basic:
enable: true
# Basic认证用户名
username: babasic
# Basic认证密码
password: BaBasic123!@#plm
## 开启生产环境屏蔽,一定要先开启knife4j增强才会生效
## You do not have permission to access this page
production: false
网关配置:
yml
knife4j:
gateway:
enabled: true
# 排序规则(tag/operation排序自4.2.0版本新增)
# 取值:alpha-默认排序规则,官方swagger-ui默认实现,order-Knife4j提供的增强排序规则,开发者可扩展x-order,根据数值来自定义排序
tags-sorter: order
operations-sorter: order
# 指定服务发现的模式聚合微服务文档
strategy: manual
routes:
- name: App1服务
# 子服务存在其他分组情况,聚合其他分组
url: /app1/v3/api-docs
# 服务名称(Optional)
service-name: baian-cloud-test-app1
# 路由前缀
context-path: /app1
# 排序
order: 1
- name: App2服务
# 子服务存在其他分组情况,聚合其他分组
url: /app2/v3/api-docs
# 服务名称(Optional)
service-name: baian-cloud-test-app2
# 路由前缀
context-path: /app2
# 排序
order: 2
- name: App3服务
# 子服务存在其他分组情况,聚合其他分组
url: /app3/v3/api-docs
# 服务名称(Optional)
service-name: baian-cloud-test-app3
# 路由前缀
context-path: /app3
# 排序
order: 3
全局添加自定义头
java
package com.baian.common.core.config;
import io.swagger.v3.oas.models.Operation;
import io.swagger.v3.oas.models.media.Schema;
import io.swagger.v3.oas.models.parameters.HeaderParameter;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import lombok.extern.slf4j.Slf4j;
import org.springdoc.core.customizers.GlobalOpenApiCustomizer;
import org.springdoc.core.customizers.GlobalOperationCustomizer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.web.method.HandlerMethod;
import java.util.List;
/**
* @program: baian-cloud
* @description: 为每个接口添加鉴权
* @author: <航迹者-694204477@qq.com>
* @create: 2024-07-02 10:21
**/
@Slf4j
@Configuration
public class Knife4jOperationCustomizer {
@Value("${sa-token.token-name:Authorization}")
private String securityHeaderName;
@Bean
public GlobalOpenApiCustomizer orderGlobalOpenApiCustomizer() {
return openApi -> {
// 全局添加鉴权参数
if (openApi.getPaths() != null) {
HeaderParameter parametersItem = new HeaderParameter();
parametersItem.setName(securityHeaderName);
parametersItem.setRequired(false);
Schema<String> schema = new Schema<>();
schema.setType("string");
parametersItem.setSchema(schema);
openApi.getPaths().forEach((s, pathItem) -> {
pathItem.readOperations().forEach(operation -> {
// 为所有接口添加请求头
operation.addParametersItem(parametersItem);
// 为所有接口添加鉴权
// operation.addSecurityItem(new SecurityRequirement().addList(HttpHeaders.AUTHORIZATION));
});
});
}
};
}
}
// https://doc.xiaominfo.com/docs/blog/add-authorization-header
注解:Springfox改用Springdoc后,注解改变:
@Api → @Tag
@ApiIgnore → @Parameter(hidden = true) or @Operation(hidden = true) or @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")
实用新增注解:
@ParameterObject
案例
@Tag(name = "用户接口")
@RestController
@RequestMapping("sys/user")
public class SysUserController {
@Resource
private ISysUserService sysUserService;
@Operation(summary = "分页查询")
@GetMapping("page")
public AjaxResult queryPage(@ParameterObject SysUserPageDTO dto) {
PageInfo page = sysUserService.queryPage(dto);
return AjaxResult.success(page);
}
@Operation(summary = "详情")
@GetMapping("{id}")
public AjaxResult queryInfo(@PathVariable Long id) {
SysUserDTO dto = sysUserService.queryById(id);
return AjaxResult.success(dto);
}
@Operation(summary = "新增")
@PostMapping
public AjaxResult save(@RequestBody SysUserDTO dto) {
Long id = sysUserService.saveInfo(dto);
return AjaxResult.success(id);
}
}
@Getter
@Setter
@TableName("user")
@Schema(name = "User", description = "$!{table.comment}")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Schema(description = "主键")
@TableId("id")
private Long id;
@Schema(description = "用户名")
@TableField("name")
private String name;
@Schema(description = "手机号")
@TableField("phone")
private String phone;
@Schema(description = "性别")
@TableField("sex")
private String sex;
@Schema(description = "状态 0:禁用,1:正常")
@TableField("status")
private Integer status;
}
其他参考:
https://blog.csdn.net/m0_74055560/article/details/134348304
福利配置: 自动转发。
java
package com.baian.common.core.config;
import io.undertow.servlet.spec.HttpServletRequestImpl;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
/**
* @program: baian-cloud
* @description: resource
* @author: <航迹者-694204477@qq.com>
* @create: 2024-07-02 08:51
**/
@RestController
@Slf4j
public class BaiAnResourceCtl {
@GetMapping("/")
public void context(HttpServletRequest request, HttpServletResponse response) throws IOException {
log.error("=====baian-cloud-common-web-core=======com.baian.common.core.config.BaiAnResourceCtl=================默认根path/====重定向到/doc.html==========");
if (request instanceof HttpServletRequestImpl undertow) {
String resolvedPath = undertow.getExchange().getResolvedPath();
response.sendRedirect(resolvedPath + "/doc.html");
return;
}
response.sendRedirect("/doc.html");
}
}