Spring AOP中如何匹配直接/间接标注父注解的类?
解决方案:匹配直接/间接标注目标注解的类
这个问题其实是Spring AOP切入点表达式的常见场景——要同时覆盖直接标注目标注解和通过元注解间接标注的类,完全不需要定义多个切入点,只需要调整切入点表达式的写法即可。
针对Spring自带的@Controller & @RestController场景
你原来的切入点只能匹配直接标注@Controller的类,要同时包含@RestController(它本身标注了@Controller),可以用这个切入点:
@Pointcut("within(@org.springframework.stereotype.Controller *) || within(@(@org.springframework.stereotype.Controller *) *)") public void controllerPointcut() {}
针对自定义父/子注解场景(你的实际需求)
假设你的ParentAnnotation全限定名是com.example.ParentAnnotation,对应的通用切入点如下:
@Pointcut("within(@com.example.ParentAnnotation *) || within(@(@com.example.ParentAnnotation *) *)") public void parentAnnotationPointcut() {}
表达式含义拆解
我们把这个复合表达式拆成两部分看:
within(@com.example.ParentAnnotation *):匹配直接标注了ParentAnnotation的类(比如你的MyClassA),覆盖类内所有方法。within(@(@com.example.ParentAnnotation *) *):匹配那些标注了「被ParentAnnotation标注的注解」的类(比如你的MyClassB标注了ChildAnnotation,而ChildAnnotation本身带ParentAnnotation),这就覆盖了间接标注的场景。
扩展:多层元注解的情况
如果你的项目中有更深层次的元注解(比如GrandChildAnnotation标注了ChildAnnotation,ChildAnnotation又标注了ParentAnnotation),只需要再叠加一层表达式即可:
@Pointcut("within(@com.example.ParentAnnotation *) " + "|| within(@(@com.example.ParentAnnotation *) *) " + "|| within(@(@(@com.example.ParentAnnotation *) *) *)") public void parentAnnotationPointcut() {}
不过绝大多数业务场景下,两层表达式就足够覆盖需求了。
内容的提问来源于stack exchange,提问作者maojf
相关产品推荐
相关产品推荐

