【问题标题】:Spring AOP pointcut for all public methods of an annotatted class (including parent class methods)注释类的所有公共方法(包括父类方法)的 Spring AOP 切入点
【发布时间】:2020-04-24 11:59:19
【问题描述】:

我有两节课

public class ParentTestClass {
    public void publicMethodOfParent() {
    }
}

@Component
@MyAnnotation
public class ChildTestClass extends ParentTestClass {
    public void publicMethodOfChild() {
    }
}

使用 Spring AOP 我需要包装:

  • 如果注释放在类级别,则对所有使用 @MyAnnotation 注释的公共方法的所有调用
  • 如果注释在方法级别,则使用@MyAnnotation 注释的所有方法。

这是我的切入点


@Around("(@within(MyAnnotation) && execution(public * *(..))) || @annotation(MyAnnotation)")
public Object myWrapper(ProceedingJoinPoint invocation) throws Throwable {
   // ...
}

这适用于ChildTestClass 的公共方法,但当我拨打电话childTestClass.publicMethodOfParent() 时,ParentTestClass#publicMethodOfParent 没有包装我如何包含父方法?

【问题讨论】:

  • 嗯......你总是可以覆盖它。
  • 是的,但是覆盖所有用法很痛苦
  • 确实如此,但最终,publicMethodOfParent 是可以通过 childClass 访问的,但它并不是 childClass 的真正方法。我认为这就是区别。

标签: java aop spring-aop pointcut


【解决方案1】:

下面的切入点表达式也会拦截父方法

来自documentation

@Pointcut("within(com.app..*) && execution(public * com.app..*.*(..))")
public void publicMethodsInApp() {
}

@Around("(publicMethodsInApp() && @target(MyAnnotation)) || "
        + "(publicMethodsInApp() && @annotation(MyAnnotation))")
public Object myWrapper(ProceedingJoinPoint invocation) throws Throwable {
 //..
}

@target:限制匹配到连接点(方法的执行时 使用 Spring AOP),其中执行对象的类具有 给定类型的注释。

【讨论】:

  • 它会起作用,但我需要一些没有类名的通用内容within(ParentTestClass)
  • 是否需要拦截如下:基于注解,拦截父方法?
  • 我在项目外部有接口,为 Spring feign 客户端定义了一些方法。这些接口由项目内部的接口扩展并标有注解。每次调用我都需要执行一个操作。所以要求是封装所有对 feign 客户端 bean 的公共方法的调用。
  • 我已经更新了不涉及引用任何类且仅基于注释的答案。这适用于您共享的示例代码。如果这不符合您的要求,您能否用需要拦截的确切代码示例更新问题?
  • 不确定您的用例,但您能否尝试缩小特定软件包中的方法,例如 && execution(public * com.path.to.your.package.*(..))) 。这是为了从匹配器中排除框架特定的类
猜你喜欢
  • 1970-01-01
  • 2011-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多