55import org .aspectj .lang .annotation .After ;
66import org .aspectj .lang .annotation .Aspect ;
77import org .aspectj .lang .annotation .Before ;
8+ import org .aspectj .lang .annotation .Pointcut ;
9+ import org .aspectj .lang .reflect .MethodSignature ;
810import org .springframework .core .annotation .Order ;
911import org .springframework .stereotype .Component ;
1012import 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