Skip to content

Commit f1f40fc

Browse files
committed
feat: 优化 DynamicDataSourceAspect,拦截类和方法上的注解
1 parent 6157483 commit f1f40fc

1 file changed

Lines changed: 20 additions & 6 deletions

File tree

simple-common/src/main/java/top/cadecode/common/datasource/DynamicDataSourceAspect.java

Lines changed: 20 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
import org.aspectj.lang.annotation.After;
66
import org.aspectj.lang.annotation.Aspect;
77
import org.aspectj.lang.annotation.Before;
8+
import org.aspectj.lang.annotation.Pointcut;
9+
import org.aspectj.lang.reflect.MethodSignature;
810
import org.springframework.core.annotation.Order;
911
import org.springframework.stereotype.Component;
1012
import top.cadecode.common.datasource.DynamicDataSource.DynamicDataSourceHolder;
@@ -23,26 +25,38 @@ public class DynamicDataSourceAspect {
2325
/**
2426
* 切换数据源
2527
*/
26-
@Before("@annotation(dataSource)")
28+
@Before("@within(dataSource) || @annotation(dataSource)")
2729
public void switchDataSource(JoinPoint point, DataSource dataSource) {
28-
String dataSourceKey = dataSource.value();
30+
// 获取方法上的注解
31+
MethodSignature methodSignature = (MethodSignature) point.getSignature();
32+
DataSource mDataSource = methodSignature.getMethod().getAnnotation(DataSource.class);
33+
// 获取数据源 key
34+
String dataSourceKey;
35+
if (mDataSource != null) {
36+
dataSourceKey = mDataSource.value();
37+
} else {
38+
// 获取取类上的注解内容
39+
dataSourceKey = methodSignature.getMethod()
40+
.getDeclaringClass().
41+
getAnnotation(DataSource.class)
42+
.value();
43+
}
44+
// 设置数据源
2945
if (!DynamicDataSourceHolder.containDataSourceKey(dataSourceKey)) {
3046
log.info("数据源 {} 不存在,将使用默认数据源", dataSource.value());
3147
} else {
32-
// 切换数据源
33-
DynamicDataSourceHolder.setDataSourceKey(dataSource.value());
48+
DynamicDataSourceHolder.setDataSourceKey(dataSourceKey);
3449
log.info("切换数据源到 {},在方法 [{}]", dataSourceKey, point.getSignature());
3550
}
3651
}
3752

3853
/**
3954
* 重置数据源
4055
*/
41-
@After("@annotation(dataSource)")
56+
@After("@within(dataSource) || @annotation(dataSource)")
4257
public void resetDataSource(JoinPoint point, DataSource dataSource) {
4358
// 将数据源重置置为默认数据源
4459
DynamicDataSourceHolder.clearDataSourceKey();
4560
log.info("重置默认数据源,在方法 [{}]", point.getSignature());
4661
}
47-
4862
}

0 commit comments

Comments
 (0)