فهرست منبع

fix 修复 多数据源aop语法错误

疯狂的狮子li 3 سال پیش
والد
کامیت
6e67e1a849

+ 2 - 1
ruoyi-demo/src/main/java/com/ruoyi/demo/service/impl/TestTreeServiceImpl.java

@@ -1,11 +1,11 @@
 package com.ruoyi.demo.service.impl;
 
 import cn.hutool.core.bean.BeanUtil;
-import com.ruoyi.common.utils.StringUtils;
 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
 import com.baomidou.mybatisplus.core.toolkit.Wrappers;
 import com.ruoyi.common.annotation.DataScope;
 import com.ruoyi.common.core.mybatisplus.core.ServicePlusImpl;
+import com.ruoyi.common.utils.StringUtils;
 import com.ruoyi.demo.domain.TestTree;
 import com.ruoyi.demo.domain.bo.TestTreeBo;
 import com.ruoyi.demo.domain.vo.TestTreeVo;
@@ -23,6 +23,7 @@ import java.util.Map;
  * @author Lion Li
  * @date 2021-07-26
  */
+//@DataSource(DataSourceType.SLAVE) // 切换从库查询
 @Service
 public class TestTreeServiceImpl extends ServicePlusImpl<TestTreeMapper, TestTree, TestTreeVo> implements ITestTreeService {
 

+ 27 - 2
ruoyi-framework/src/main/java/com/ruoyi/framework/aspectj/DataSourceAspect.java

@@ -6,9 +6,14 @@ import com.ruoyi.common.utils.StringUtils;
 import org.aspectj.lang.ProceedingJoinPoint;
 import org.aspectj.lang.annotation.Around;
 import org.aspectj.lang.annotation.Aspect;
+import org.aspectj.lang.annotation.Pointcut;
+import org.aspectj.lang.reflect.MethodSignature;
+import org.springframework.core.annotation.AnnotationUtils;
 import org.springframework.core.annotation.Order;
 import org.springframework.stereotype.Component;
 
+import java.util.Objects;
+
 /**
  * 多数据源处理
  *
@@ -19,8 +24,15 @@ import org.springframework.stereotype.Component;
 @Component
 public class DataSourceAspect {
 
-	@Around("@annotation(dataSource) || @within(dataSource)")
-	public Object around(ProceedingJoinPoint point, DataSource dataSource) throws Throwable {
+	@Pointcut("@annotation(com.ruoyi.common.annotation.DataSource)"
+			+ "|| @within(com.ruoyi.common.annotation.DataSource)")
+	public void dsPointCut() {
+	}
+
+	@Around("dsPointCut()")
+	public Object around(ProceedingJoinPoint point) throws Throwable {
+		DataSource dataSource = getDataSource(point);
+
 		if (StringUtils.isNotNull(dataSource)) {
 			DynamicDataSourceContextHolder.poll();
 			String source = dataSource.value().getSource();
@@ -35,4 +47,17 @@ public class DataSourceAspect {
 		}
 	}
 
+	/**
+	 * 获取需要切换的数据源
+	 */
+	public DataSource getDataSource(ProceedingJoinPoint point) {
+		MethodSignature signature = (MethodSignature) point.getSignature();
+		DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class);
+		if (Objects.nonNull(dataSource)) {
+			return dataSource;
+		}
+
+		return AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class);
+	}
+
 }