懒羊羊
2024-01-31 e57a8990ae56f657a59c435a0613c5f7a8728003
提交 | 用户 | 时间
e57a89 1 package com.jcdm.framework.aspectj;
2
3 import java.util.Objects;
4 import org.aspectj.lang.ProceedingJoinPoint;
5 import org.aspectj.lang.annotation.Around;
6 import org.aspectj.lang.annotation.Aspect;
7 import org.aspectj.lang.annotation.Pointcut;
8 import org.aspectj.lang.reflect.MethodSignature;
9 import org.slf4j.Logger;
10 import org.slf4j.LoggerFactory;
11 import org.springframework.core.annotation.AnnotationUtils;
12 import org.springframework.core.annotation.Order;
13 import org.springframework.stereotype.Component;
14 import com.jcdm.common.annotation.DataSource;
15 import com.jcdm.common.utils.StringUtils;
16 import com.jcdm.framework.datasource.DynamicDataSourceContextHolder;
17
18 /**
19  * 多数据源处理
20  * 
21  * @author jc
22  */
23 @Aspect
24 @Order(1)
25 @Component
26 public class DataSourceAspect
27 {
28     protected Logger logger = LoggerFactory.getLogger(getClass());
29
30     @Pointcut("@annotation(com.jcdm.common.annotation.DataSource)"
31             + "|| @within(com.jcdm.common.annotation.DataSource)")
32     public void dsPointCut()
33     {
34
35     }
36
37     @Around("dsPointCut()")
38     public Object around(ProceedingJoinPoint point) throws Throwable
39     {
40         DataSource dataSource = getDataSource(point);
41
42         if (StringUtils.isNotNull(dataSource))
43         {
44             DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
45         }
46
47         try
48         {
49             return point.proceed();
50         }
51         finally
52         {
53             // 销毁数据源 在执行方法之后
54             DynamicDataSourceContextHolder.clearDataSourceType();
55         }
56     }
57
58     /**
59      * 获取需要切换的数据源
60      */
61     public DataSource getDataSource(ProceedingJoinPoint point)
62     {
63         MethodSignature signature = (MethodSignature) point.getSignature();
64         DataSource dataSource = AnnotationUtils.findAnnotation(signature.getMethod(), DataSource.class);
65         if (Objects.nonNull(dataSource))
66         {
67             return dataSource;
68         }
69
70         return AnnotationUtils.findAnnotation(signature.getDeclaringType(), DataSource.class);
71     }
72 }