切点

AspectJExpressionPointcut

notion image
只能匹配方法信息
  1. execution()匹配方法名称,参数,返回值
  1. @annotation 只能匹配方法上的注解
通过实现 MethodMatcher 接口, 用来执行方法的匹配
public class A16 { public static void main(String[] args) throws NoSuchMethodException { AspectJExpressionPointcut pt1 = new AspectJExpressionPointcut(); //设置切点表达式 pt1.setExpression("execution(* bar())"); System.out.println(pt1.matches(T1.class.getMethod("foo"), T1.class)); System.out.println(pt1.matches(T1.class.getMethod("bar"), T1.class)); AspectJExpressionPointcut pt2 = new AspectJExpressionPointcut(); //设置注解表达式 pt2.setExpression("@annotation(org.springframework.transaction.annotation.Transactional)"); System.out.println(pt2.matches(T1.class.getMethod("foo"), T1.class)); System.out.println(pt2.matches(T1.class.getMethod("bar"), T1.class)); /* 学到了什么 a. 底层切点实现是如何匹配的: 调用了 aspectj 的匹配方法 b. 比较关键的是它实现了 MethodMatcher 接口, 用来执行方法的匹配 */ } static class T1 { @Transactional public void foo() { } public void bar() { } } @Transactional static class T2 { public void foo() { } } @Transactional interface I3 { void foo(); } static class T3 implements I3 { public void foo() { } } }
输出
false true true false
 

StaticMethodMatcherPointcut

实现抽象类StaticMethodMatcherPointcut的抽象方法matches
notion image
StaticMethodMatcherPointcut pt3 = new StaticMethodMatcherPointcut() { @Override public boolean matches(Method method, Class<?> targetClass) { // 检查方法上是否加了 Transactional 注解 MergedAnnotations annotations = MergedAnnotations.from(method); if (annotations.isPresent(Transactional.class)) { return true; } // 查看类上是否加了 Transactional 注解 MergedAnnotations.SearchStrategy.TYPE_HIERARCH 搜索本类以及继承的类或者实现的接口 annotations = MergedAnnotations.from(targetClass, MergedAnnotations.SearchStrategy.TYPE_HIERARCHY); if (annotations.isPresent(Transactional.class)) { return true; } return false; } }; System.out.println(pt3.matches(T1.class.getMethod("foo"), T1.class)); System.out.println(pt3.matches(T1.class.getMethod("bar"), T1.class)); System.out.println(pt3.matches(T2.class.getMethod("foo"), T2.class)); System.out.println(pt3.matches(T3.class.getMethod("foo"), T3.class));
输出
true false true true