切面+自定義注解的使用


1.applicationContext.xml中開啟注解掃描

<context:component-scan base-package="com.lcb,com.lcb.soa.store.item" />

2.自定義注解

1 @Target(ElementType.METHOD)
2 @Retention(RetentionPolicy.RUNTIME)
3 @Documented
4 @Inherited
5 public @interface DateBaseName {
6 
7     String dataBaseName() default "";
8 }


3.定義切面類

 1 /**
 2  * @author caiyike
 3  * @version 1.0
 4  * @date 2019-02-26 15:26
 5  */
 6 @Aspect
 7 @Component
 8 public class DataBaseManager {
 9 
10     @Pointcut("execution(* com.lcb.soa.store.item.test..*.*(..)) ")
11     private void useDateBaseByName() {
12     }
13 
14 
15     @Around("useDateBaseByName()")
16     public Object useMaster(ProceedingJoinPoint joinPoint) throws Throwable {
17         Object[] args = joinPoint.getArgs();
18         Method method = getMethod(joinPoint, args);
19         //獲取數據庫名稱參數
20         String oldDataSource = DataSourceContextHolder.getRuntimeDataSourceKey();
21         DateBaseName chooseDataSource = method.getAnnotation(DateBaseName.class);
22         if(chooseDataSource != null){
23             String dataBaseName = chooseDataSource.dataBaseName();
24             DataSourceContextHolder.setDataSourceKey(dataBaseName);
25             try {
26                 Object proceed = joinPoint.proceed();
27                 DataSourceContextHolder.setDataSourceKey(oldDataSource);
28                 return proceed;
29             } catch (Throwable e) {
30                 throw e;
31             } finally {
32                 DataSourceContextHolder.clearDataSourceKey();
33             }
34         }else {
35             Object proceed = joinPoint.proceed();
36             DataSourceContextHolder.setDataSourceKey(oldDataSource);
37             return proceed;
38         }
39 
40     }
41 
42     private Method getMethod(ProceedingJoinPoint joinPoint, Object[] args) throws NoSuchMethodException {
43         String methodName = joinPoint.getSignature().getName();
44         Class clazz = joinPoint.getTarget().getClass();
45         Method[] methods = clazz.getMethods();
46         for (Method method : methods) {
47             if (methodName.equals(method.getName())) {
48                 return method;
49             }
50         }
51         return null;
52     }
53 }

4.Method上使用自定義注解

@DateBaseName(dataBaseName = "masterStoreItem")
public void method(){}

AOP中pointcut expression表達式參考

https://blog.csdn.net/kkdelta/article/details/7441829 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM