Spring AOP - Point Cut没有被调用

时间:2018-01-13 19:35:11

标签: java spring spring-aop aspect

我有一个SpringBoot应用程序。 我已经定义了一个Annotation说" Track",并且我在不同的包中注释了一些我想要aop考虑的方法。 注释定义如下:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Track {

}

我没有错过我的包的@Configuration类中的@EnableAspectJAutoProxy。

我在Aspect中定义了一个Pointcut和一个建议,如下所示:

@Aspect
@Component
public class MyAspect {

@Pointcut("execution(@Track * *.*(..))")
void annotatedMethod() {
    // No Implementation required
}

@Around("annotatedMethod() && @annotation(methodLevelTrack)")
public void adviseAnnotatedMethods(ProceedingJoinPoint proceedingJoinPoint,
        Track methodLevelTrack) throws Throwable {

     // do some task
    proceedingJoinPoint.proceed();
    // do some task after the method is executed.
  }
}

我的意图是:对于任何包中的任何方法(使用@Track注释),任何访问修饰符,以及任意数量的输入参数和任何返回类型,都要遵循方面的@Around建议。

现在,有趣的情况如下: 我有一个班级说"引擎"它调用其他类和下游系统来执行长时间运行的操作。让我们按如下方式定义类:

public class Engine {
  // bunch of other autowired objects

 public void processTask() {
   <autowired_object_A>.someMethod() // this method has been annotated with @Track
   <autowired_object_B>.someMethod() // this method has also been annotated with @ Track
   .... // bunch of other methods in other autowired objects that have been annotated with @ Track

   someMethodOfEngineClass(); // Now this has been defined in the Engine class as below, but pointcut doesn't recognize this method!

 }

 @Track
 private void someMethodOfEngineClass() {
  // do something
 }
}

所有&#34;其他&#34;自动对象&#39;方法被切入点按预期识别,但此Engine类中的方法(已使用@Track注释)无法识别。什么是神秘的?

我试过制作&#34; someMethodOfEngineClass&#34;方法公开,返回一些东西而不是虚空和所有这些组合,它不起作用。

我错过了什么? 它是切入点定义表达式吗? 我在其中一个子包中定义了方面,是否应该在包结构的顶层定义方面?

请问大家请提出一些可行的方法吗?我有点坚持这个。

1 个答案:

答案 0 :(得分:1)

当你定义aop spring在类周围创建代理时, 因此,当调用该方法时,实际上将调用委托给代理,就像

一样
your.package.Engine$$FastClassBySpringCGLIB$$c82923b4.someMethodOfEngineClass()

但这只适用于从其外部调用方法的方法 如果您从同一个类调用class方法,则可以通过this.someMethodOfEngineClass()

实际调用它

这里 - &gt; http://www.nurkiewicz.com/2011/10/spring-pitfalls-proxying.html 你可以找到更多关于代理的信息

因此绕过代理并且aop无效。