切面+自定义注解的使用


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