如何修改Spring AOP execution表达式匹配指定注解与类型的方法参数
解决方案:修改Spring AOP切点表达式匹配目标方法
要实现匹配**参数带有@AnnotationA注解、类型为SomeType,且允许该参数前后有任意注解(或无其他注解)**的方法,你需要调整切点表达式,覆盖参数注解的所有可能顺序场景:
最终切点表达式
@Around("execution(* *(.., (@com.a.b.AnnotationA com.example.SomeType), ..)) || " + "execution(* *(.., (@com.a.b.AnnotationA @* com.example.SomeType), ..)) || " + "execution(* *(.., (@* com.a.b.AnnotationA com.example.SomeType), ..)) || " + "execution(* *(.., (@* com.a.b.AnnotationA @* com.example.SomeType), ..))")
表达式说明
该表达式通过||组合四种场景,覆盖所有符合要求的参数注解情况:
(@com.a.b.AnnotationA com.example.SomeType):参数仅带有@AnnotationA注解,类型为SomeType(@com.a.b.AnnotationA @* com.example.SomeType):@AnnotationA在其他注解之前,参数类型为SomeType(@* com.a.b.AnnotationA com.example.SomeType):@AnnotationA在其他注解之后,参数类型为SomeType(@* com.a.b.AnnotationA @* com.example.SomeType):@AnnotationA前后都有其他注解,参数类型为SomeType
其中@*表示匹配任意单个注解,通过组合这四种场景,就能精准匹配你列出的所有目标方法。
验证匹配场景
该表达式会匹配以下所有方法:
// 仅带@AnnotationA的SomeType参数 doSth(@AnnotationA SomeType param) // @AnnotationA在@AnnotationB之前 doSth(@AnnotationA @AnnotationB SomeType param) // @AnnotationA在@AnnotationB之后 doSth(@AnnotationB @AnnotationA SomeType param) // @AnnotationA前后都有其他注解 doSth(@AnnotationC @AnnotationA @AnnotationB SomeType param)
内容的提问来源于stack exchange,提问作者kamroj
相关产品推荐
相关产品推荐

