@Transactional注解的切点匹配
前面切点表达式的匹配方法有一定的局限性,当注解在类或接口上的时候不能匹配。下面是另一种处理注解的切点匹配方式。
1.类的准备
static class T1{@Transactionalpublic void foo(){}public void bar(){}}@Transactionalstatic class T2{public void foo(){}}@Transactionalinterface I3{void foo();}static class T3 implements I3{public void foo(){}}
2.主要方法
public static void main(String[] args) throws NoSuchMethodException {/*AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();pointcut.setExpression("execution(* bar())");System.out.println(pointcut.matches(T1.class.getMethod("foo"),T1.class));System.out.println(pointcut.matches(T1.class.getMethod("bar"),T1.class));AspectJExpressionPointcut pointcut1 = new AspectJExpressionPointcut();pointcut1.setExpression("@annotation(org.springframework.transaction.annotation.Transactional)");System.out.println(pointcut1.matches(T1.class.getMethod("foo"),T1.class));System.out.println(pointcut1.matches(T1.class.getMethod("bar"),T1.class));
*/StaticMethodMatcherPointcut pointcut2 = new StaticMethodMatcherPointcut() {@Overridepublic boolean matches(Method method, Class<?> targetClass) {//检查方法上是否加了Transactional注解MergedAnnotations annotations = MergedAnnotations.from(method);if (annotations.isPresent(Transactional.class)) {return true;}//查看类上是否加了Transactional注解annotations = MergedAnnotations.from(targetClass,MergedAnnotations.SearchStrategy.TYPE_HIERARCHY);if (annotations.isPresent(Transactional.class)) {return true;}return false;}};System.out.println(pointcut2.matches(T1.class.getMethod("foo"),T1.class));System.out.println(pointcut2.matches(T1.class.getMethod("bar"),T1.class));System.out.println(pointcut2.matches(T2.class.getMethod("foo"),T2.class));System.out.println(pointcut2.matches(T3.class.getMethod("foo"),T3.class));}
使用StaticMethodMatcherPointcut进行注解的匹配。
1)重写matches方法
2)检查方法上的注解
3)检查类上是否加了注解
annotations = MergedAnnotations.from(targetClass,MergedAnnotations.SearchStrategy.TYPE_HIERARCHY);
该方法会搜索类上以及继承树上的类或接口。
结果打印:

