execution (常用,方法级别的匹配)
语法:
execution(modifiers-pattern? ret-type-pattern declaring-type-pattern?name-pattern(param-pattern) throws-pattern?)
(注:返回值类型 & 参数类型支持泛型判断)
带有?的位,非必写,即可省略。所以,一个表达式至少由3部分组成。例:
// 匹配所有方法
execution(* *(..))
若该位省略,例modifiers-pattern,意味着匹配该位能匹配的全部方法:public、protected、default修饰的方法
上例子:
@Pointcut("execution(public java.util.List<java.lang.Integer> *.test(java.util.List<java.lang.String>) throws java.lang.RuntimeException)")
匹配所有的方法名为test,方法格式为下方格式的方法。
public List<Iteger> test(List<String> list) throws RuntimeException
通配符
上例子:
// 1. 关于 .. 通配符
// 匹配子孙包下的所有类的所有方法
execution(* life.cqq..*.*(..))// 2. 关于 * 通配符
// 匹配所有类的所有方法
execution(* *(..))// 匹配子孙包下带有指定前缀的包下的所有类的所有方法
execution(* life.cqq..prefix*.*.*(..))// 3. 关于 + 通配符
// 匹配子孙包下继承或实现了指定类型的类 以及 该类型的本类(若该类型不为接口) 下的所有方法
execution(* life.cqq..type+.*(..))
within (常用,类级别的匹配) 语法:
within(declaring-type-pattern)
execution语法中的declaring-type-pattern部分,从通配符的例子中提取出可应用于within的内容:
// 1. 关于 .. 通配符
// 匹配子孙包下的所有类的所有方法
within(life.cqq..*)// 2. 关于 * 通配符
// 匹配所有类的所有方法
within(*)// 匹配子孙包下带有指定前缀的包下的所有类的所有方法
within(life.cqq..prefix*.*)// 3. 关于 + 通配符
// 匹配子孙包下继承或实现了指定类型的类 以及 该类型的本类(若该类型不为接口) 下的所有方法
within(life.cqq..type+)
@annotation (常用,方法级别的匹配)
语法:
@annotation(annotation-type-pattern)
与execution一样针对于方法,匹配添加了指定注解的方法。
@within (常用,类级别的匹配)
语法:
@within(annotation-type-pattern)
与within一样针对于类,匹配添加了指定注解的类。
逻辑运算符
应用在多个Point上组成稍微复杂的匹配表达式
上例子:
@Component class AopBean { public void test(String str) { System.out.println("String"); } public void test(Integer integer) { System.out.println("Integer"); } } @Pointcut("within(life.cqq.aop.logicsymbol.AopBean)") public void point1() {} @Pointcut("execution(public void test(java.lang.String))") public void point2() {} @Pointcut("execution(public void test(java.lang.Integer))") public void point3() {} // @Around("point1() && point2()") : 匹配参数为String类型的方法 // @Around("point1() && (point2() || point3())") : 匹配参数为Integer、String类型的方法 // @Around("point1() && !point2())") : 匹配参数为Integer类型的方法
以上仅为平时常用的内容,还有其他许多写法,如:args、@args、target、@target等
一次实际应用
需求:
@Pointcut("execution(* life.cqq..controller.*.*(..))") private void log() {} @Pointcut("@within(life.cqq.common.newlog.annotation.AppOpnLog) || @annotation(life.cqq.common.newlog.annotation.AppOpnLog)") public void appOpnLog() { } @Pointcut("@within(life.cqq.common.newlog.annotation.EsOpnLog) || @annotation(life.cqq.common.newlog.annotation.EsOpnLog)") public void esOpnLog() { } @Pointcut("@within(life.cqq.common.newlog.annotation.WebOpnLog) || @annotation(life.cqq.common.newlog.annotation.WebOpnLog)") public void webOpnLog() { } @Around("appOpnLog() || esOpnLog() || webOpnLog()") public Object opnLogAround(ProceedingJoinPoint point) throws Throwable { // ...... return point.proceed(); }