切面+自定义注解的使用

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 

 

posted @ 2019-02-27 10:25  Joke科  阅读(1843)  评论(0编辑  收藏  举报