refactor: springdoc 替换 springfox

This commit is contained in:
xingyu4j
2022-12-09 13:43:15 +08:00
parent 02174383a7
commit 9fc6e0f00b
469 changed files with 3317 additions and 3721 deletions

View File

@@ -59,9 +59,13 @@
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<scope>provided</scope> <!-- 设置为 provided主要是 PageParam 使用到 -->
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-webmvc-core</artifactId>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-javadoc</artifactId>
</dependency>
<!-- 监控相关 -->

View File

@@ -1,7 +1,6 @@
package cn.iocoder.yudao.framework.common.pojo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import javax.validation.constraints.Min;
@@ -9,19 +8,19 @@ import javax.validation.constraints.Max;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
@ApiModel("分页参数")
@Schema(title="分页参数")
@Data
public class PageParam implements Serializable {
private static final Integer PAGE_NO = 1;
private static final Integer PAGE_SIZE = 10;
@ApiModelProperty(value = "页码,从 1 开始", required = true,example = "1")
@Schema(title = "页码,从 1 开始", required = true,example = "1")
@NotNull(message = "页码不能为空")
@Min(value = 1, message = "页码最小值为 1")
private Integer pageNo = PAGE_NO;
@ApiModelProperty(value = "每页条数,最大值为 100", required = true, example = "10")
@Schema(title = "每页条数,最大值为 100", required = true, example = "10")
@NotNull(message = "每页条数不能为空")
@Min(value = 1, message = "每页条数最小值为 1")
@Max(value = 100, message = "每页条数最大值为 100")

View File

@@ -1,21 +1,19 @@
package cn.iocoder.yudao.framework.common.pojo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
@ApiModel("分页结果")
@Schema(title = "分页结果")
@Data
public final class PageResult<T> implements Serializable {
@ApiModelProperty(value = "数据", required = true)
@Schema(title = "数据", required = true)
private List<T> list;
@ApiModelProperty(value = "总量", required = true)
@Schema(title = "总量", required = true)
private Long total;
public PageResult() {

View File

@@ -1,8 +1,8 @@
package cn.iocoder.yudao.framework.operatelog.core.annotations;
import cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;

View File

@@ -15,8 +15,8 @@ import cn.iocoder.yudao.framework.operatelog.core.service.OperateLog;
import cn.iocoder.yudao.framework.operatelog.core.service.OperateLogFrameworkService;
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
import com.google.common.collect.Maps;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
@@ -71,15 +71,15 @@ public class OperateLogAspect {
@Resource
private OperateLogFrameworkService operateLogFrameworkService;
@Around("@annotation(apiOperation)")
public Object around(ProceedingJoinPoint joinPoint, ApiOperation apiOperation) throws Throwable {
@Around("@annotation(operation)")
public Object around(ProceedingJoinPoint joinPoint, Operation operation) throws Throwable {
// 可能也添加了 @ApiOperation 注解
cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog operateLog = getMethodAnnotation(joinPoint,
cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog.class);
return around0(joinPoint, operateLog, apiOperation);
return around0(joinPoint, operateLog, operation);
}
@Around("!@annotation(io.swagger.annotations.ApiOperation) && @annotation(operateLog)")
@Around("!@annotation(io.swagger.v3.oas.annotations.Operation) && @annotation(operateLog)")
// 兼容处理,只添加 @OperateLog 注解的情况
public Object around(ProceedingJoinPoint joinPoint,
cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog operateLog) throws Throwable {
@@ -88,7 +88,7 @@ public class OperateLogAspect {
private Object around0(ProceedingJoinPoint joinPoint,
cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog operateLog,
ApiOperation apiOperation) throws Throwable {
Operation operation) throws Throwable {
// 目前,只有管理员,才记录操作日志!所以非管理员,直接调用,不进行记录
Integer userType = WebFrameworkUtils.getLoginUserType();
if (!Objects.equals(userType, UserTypeEnum.ADMIN.getValue())) {
@@ -101,10 +101,10 @@ public class OperateLogAspect {
// 执行原有方法
Object result = joinPoint.proceed();
// 记录正常执行时的操作日志
this.log(joinPoint, operateLog, apiOperation, startTime, result, null);
this.log(joinPoint, operateLog, operation, startTime, result, null);
return result;
} catch (Throwable exception) {
this.log(joinPoint, operateLog, apiOperation, startTime, null, exception);
this.log(joinPoint, operateLog, operation, startTime, null, exception);
throw exception;
} finally {
clearThreadLocal();
@@ -129,7 +129,7 @@ public class OperateLogAspect {
private void log(ProceedingJoinPoint joinPoint,
cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog operateLog,
ApiOperation apiOperation,
Operation operation,
LocalDateTime startTime, Object result, Throwable exception) {
try {
// 判断不记录的情况
@@ -137,16 +137,16 @@ public class OperateLogAspect {
return;
}
// 真正记录操作日志
this.log0(joinPoint, operateLog, apiOperation, startTime, result, exception);
this.log0(joinPoint, operateLog, operation, startTime, result, exception);
} catch (Throwable ex) {
log.error("[log][记录操作日志时,发生异常,其中参数是 joinPoint({}) operateLog({}) apiOperation({}) result({}) exception({}) ]",
joinPoint, operateLog, apiOperation, result, exception, ex);
joinPoint, operateLog, operation, result, exception, ex);
}
}
private void log0(ProceedingJoinPoint joinPoint,
cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog operateLog,
ApiOperation apiOperation,
Operation operation,
LocalDateTime startTime, Object result, Throwable exception) {
OperateLog operateLogObj = new OperateLog();
// 补全通用字段
@@ -155,7 +155,7 @@ public class OperateLogAspect {
// 补充用户信息
fillUserFields(operateLogObj);
// 补全模块信息
fillModuleFields(operateLogObj, joinPoint, operateLog, apiOperation);
fillModuleFields(operateLogObj, joinPoint, operateLog, operation);
// 补全请求信息
fillRequestFields(operateLogObj);
// 补全方法信息
@@ -173,21 +173,21 @@ public class OperateLogAspect {
private static void fillModuleFields(OperateLog operateLogObj,
ProceedingJoinPoint joinPoint,
cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog operateLog,
ApiOperation apiOperation) {
Operation operation) {
// module 属性
if (operateLog != null) {
operateLogObj.setModule(operateLog.module());
}
if (StrUtil.isEmpty(operateLogObj.getModule())) {
Api api = getClassAnnotation(joinPoint, Api.class);
if (api != null) {
// 优先读取 @API 的 name 属性
if (StrUtil.isNotEmpty(api.value())) {
operateLogObj.setModule(api.value());
Tag tag = getClassAnnotation(joinPoint, Tag.class);
if (tag != null) {
// 优先读取 @Tag 的 name 属性
if (StrUtil.isNotEmpty(tag.name())) {
operateLogObj.setModule(tag.name());
}
// 没有的话,读取 @API 的 tags 属性
if (StrUtil.isEmpty(operateLogObj.getModule()) && ArrayUtil.isNotEmpty(api.tags())) {
operateLogObj.setModule(api.tags()[0]);
// 没有的话,读取 @API 的 description 属性
if (StrUtil.isEmpty(operateLogObj.getModule()) && ArrayUtil.isNotEmpty(tag.description())) {
operateLogObj.setModule(tag.description());
}
}
}
@@ -195,8 +195,8 @@ public class OperateLogAspect {
if (operateLog != null) {
operateLogObj.setName(operateLog.name());
}
if (StrUtil.isEmpty(operateLogObj.getName()) && apiOperation != null) {
operateLogObj.setName(apiOperation.value());
if (StrUtil.isEmpty(operateLogObj.getName()) && operation != null) {
operateLogObj.setName(operation.description());
}
// type 属性
if (operateLog != null && ArrayUtil.isNotEmpty(operateLog.type())) {

View File

@@ -34,17 +34,18 @@
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>io.swagger</groupId>
<artifactId>swagger-annotations</artifactId>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-webmvc-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-javadoc</artifactId>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-security</artifactId>
</dependency>
<dependency>

View File

@@ -1,119 +1,60 @@
package cn.iocoder.yudao.framework.swagger.config;
import cn.iocoder.yudao.framework.swagger.core.SpringFoxHandlerProviderBeanPostProcessor;
import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.ExternalDocumentation;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.info.License;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springdoc.core.GroupedOpenApi;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ExampleBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestParameterBuilder;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
import java.util.Collections;
import java.util.List;
import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.HEADER_TENANT_ID;
import static springfox.documentation.builders.RequestHandlerSelectors.basePackage;
/**
* Swagger2 自动配置类
* Swagger3 自动配置类
*
* @author 芋道源码
*/
@AutoConfiguration
@EnableSwagger2
@EnableKnife4j
@ConditionalOnClass({Docket.class, ApiInfoBuilder.class})
@ConditionalOnClass({OpenAPI.class})
// 允许使用 swagger.enable=false 禁用 Swagger
@ConditionalOnProperty(prefix = "yudao.swagger", value = "enable", matchIfMissing = true)
@EnableConfigurationProperties(SwaggerProperties.class)
public class YudaoSwaggerAutoConfiguration {
@Bean
public SpringFoxHandlerProviderBeanPostProcessor springFoxHandlerProviderBeanPostProcessor() {
return new SpringFoxHandlerProviderBeanPostProcessor();
public OpenAPI createRestApi(SwaggerProperties properties) {
return new OpenAPI()
.info(new Info().title(properties.getTitle())
.description(properties.getDescription())
.version(properties.getVersion())
.license(new License().name("MIT").url("https://gitee.com/zhijiantianya/ruoyi-vue-pro/blob/master/LICENSE")))
.externalDocs(new ExternalDocumentation()
.description(properties.getDescription())
.url("https://gitee.com/zhijiantianya/ruoyi-vue-pro"));
}
@Bean
public Docket createRestApi(SwaggerProperties properties) {
// 创建 Docket 对象
return new Docket(DocumentationType.SWAGGER_2)
// ① 用来创建该 API 的基本信息,展示在文档的页面中(自定义展示的信息)
.apiInfo(apiInfo(properties))
// ② 设置扫描指定 package 包下的
.select()
.apis(basePackage(properties.getBasePackage()))
// .apis(basePackage("cn.iocoder.yudao.module.system")) // 可用于 swagger 无法展示时使用
.paths(PathSelectors.any())
.build()
// ③ 安全上下文(认证)
.securitySchemes(securitySchemes())
.securityContexts(securityContexts())
// ④ 全局参数(多租户 header
.globalRequestParameters(globalRequestParameters());
}
// ========== apiInfo ==========
/**
* API 摘要信息
*/
private static ApiInfo apiInfo(SwaggerProperties properties) {
return new ApiInfoBuilder()
.title(properties.getTitle())
.description(properties.getDescription())
.contact(new Contact(properties.getAuthor(), null, null))
.version(properties.getVersion())
public GroupedOpenApi publicApi() {
return GroupedOpenApi.builder()
.group("app")
.pathsToMatch("/app/**")
.build();
}
// ========== securitySchemes ==========
/**
* 安全模式,这里配置通过请求头 Authorization 传递 token 参数
*/
private static List<SecurityScheme> securitySchemes() {
return Collections.singletonList(new ApiKey(HttpHeaders.AUTHORIZATION, "Authorization", "header"));
@Bean
public GroupedOpenApi adminApi() {
return GroupedOpenApi.builder()
.group("admin")
.pathsToMatch("/admin/**")
.build();
}
/**
* 安全上下文
*
* @see #securitySchemes()
* @see #authorizationScopes()
*/
private static List<SecurityContext> securityContexts() {
return Collections.singletonList(SecurityContext.builder()
.securityReferences(securityReferences())
// 通过 PathSelectors.regex("^(?!auth).*$"),排除包含 "auth" 的接口不需要使用securitySchemes
.operationSelector(o -> o.requestMappingPattern().matches("^(?!auth).*$"))
.build());
}
private static List<SecurityReference> securityReferences() {
return Collections.singletonList(new SecurityReference(HttpHeaders.AUTHORIZATION, authorizationScopes()));
}
private static AuthorizationScope[] authorizationScopes() {
return new AuthorizationScope[]{new AuthorizationScope("global", "accessEverything")};
}
// ========== globalRequestParameters ==========
private static List<RequestParameter> globalRequestParameters() {
RequestParameterBuilder tenantParameter = new RequestParameterBuilder()
.name(HEADER_TENANT_ID).description("租户编号")
.in(ParameterType.HEADER).example(new ExampleBuilder().value(1L).build());
return Collections.singletonList(tenantParameter.build());
}
}

View File

@@ -1,43 +1,43 @@
package cn.iocoder.yudao.framework.swagger.core;
import cn.hutool.core.util.ReflectUtil;
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import java.util.List;
/**
* 解决 SpringFox 与 SpringBoot 2.6.x 不兼容的问题
* 该问题对应的 issue 为 https://github.com/springfox/springfox/issues/3462
*
* @author 芋道源码
*/
public class SpringFoxHandlerProviderBeanPostProcessor implements BeanPostProcessor {
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
}
return bean;
}
private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
// 移除,只保留 patternParser
List<T> copy = CollectionUtils.filterList(mappings, mapping -> mapping.getPatternParser() == null);
// 添加到 mappings 中
mappings.clear();
mappings.addAll(copy);
}
@SuppressWarnings("unchecked")
private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
return (List<RequestMappingInfoHandlerMapping>)
ReflectUtil.getFieldValue(bean, "handlerMappings");
}
}
//package cn.iocoder.yudao.framework.swagger.core;
//
//import cn.hutool.core.util.ReflectUtil;
//import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
//import org.springframework.beans.BeansException;
//import org.springframework.beans.factory.config.BeanPostProcessor;
//import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
//import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
//import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
//
//import java.util.List;
//
///**
// * 解决 SpringFox 与 SpringBoot 2.6.x 不兼容的问题
// * 该问题对应的 issue 为 https://github.com/springfox/springfox/issues/3462
// *
// * @author 芋道源码
// */
//public class SpringFoxHandlerProviderBeanPostProcessor implements BeanPostProcessor {
//
// @Override
// public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
// if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
// customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
// }
// return bean;
// }
//
// private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
// // 移除,只保留 patternParser
// List<T> copy = CollectionUtils.filterList(mappings, mapping -> mapping.getPatternParser() == null);
// // 添加到 mappings 中
// mappings.clear();
// mappings.addAll(copy);
// }
//
// @SuppressWarnings("unchecked")
// private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
// return (List<RequestMappingInfoHandlerMapping>)
// ReflectUtil.getFieldValue(bean, "handlerMappings");
// }
//
//}