Aspect不从Scheduled捕获方法 [英] Aspect does not capture method from Scheduled

查看:265
本文介绍了Aspect不从Scheduled捕获方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么将注释设置为cron中的方法时,注释的设置方面不起作用.

Why is set aspect of an annotation not working when it is set to a method from cron.

@Component
public class MyClass {
  @Scheduled(cron = "0/5 * * * * ?")
  public void schedule() {
    myMethod("test");
  }

  @MyAnno(cl = MyClass.class, description = "desc")
  private void myMethod(String text) {

  }
}

@Aspect
@Component
public MyAscpect {
  @Before("@annotation(myAnnoAnnotation)")
  public void myAnnoAspect(JoinPoint jp, MyAnno myAnnoAnnotation) {
}

推荐答案

Spring AOP

关于Spring AOP,您应该记住以下几点,

Spring AOP

Here are the points you should remember about Spring AOP,

由于Spring的AOP框架基于代理的性质,根据定义,目标对象内的调用不会被拦截.

Due to the proxy-based nature of Spring’s AOP framework, calls within the target object are by definition not intercepted.

  • 对于 JDK代理,只能拦截代理上的公共接口方法调用.使用 CGLIB 公共受保护的方法,代理上的调用将被拦截,甚至打包-可见的方法.

    For JDK proxies, only public interface method calls on the proxy can be intercepted. With CGLIB, public and protected method calls on the proxy will be intercepted, and even package-visible methods if necessary.

  • 您可以找到更多的

  • 由于方法myMethod私有,因此不会拦截对myMethod的调用.请参考上面提到的第二点.
  • 即使您的myMethod公开,如果通过schedule方法进行的调用也不会被拦截.请参考上面提到的第一点.
  • 现在,如果您的myMethod公开,则如果直接从对象外部对myMethod方法进行调用,则会拦截对myMethod的调用.
    • Since your method myMethod is private, the call to myMethod will not be intercepted. Please refer to the second point mentioned above.
    • Even if your myMethod was public, the call to myMethod would not have been intercepted if the call was made via schedule method. Please refer to the first point mentioned above.
    • Now if your myMethod was public, the call to myMethod would be intercepted if the call was made directly to myMethod method from outside the object.

    但是,您可以利用AspectJ源代码编织来拦截私有方法.在源代码编织中,编织器成为编译器的一部分. 编织器通过处理源代码并生成编织的Java字节码来充当编译器.代替javac编译器,它使用ajc编译器.

    However, you can intercept private methods by taking advantage of AspectJ source weaving. In source weaving, the weaver becomes part of the compiler. The weaver acts as a compiler by processing the source code and generating woven Java bytecode. Instead of javac compiler, it uses ajc compiler.

    这是您需要进行的更改:

    Here are the changes you need to make:

    • 将Maven aspectj-maven-plugin插件添加到您的pom.xml
    • 如下所示,更改了MyAspect的切入点,以包含私有方法.

    • Add Maven aspectj-maven-plugin plugin to your pom.xml
    • As shown below, changes to the pointcut of MyAspect to include private methods.

    @Component
    @Aspect
    public class MyAspect {
    
        @Before("@annotation(myAnnoAnnotation) && execution(private * *(..))")
        public void myAnnoAspect(JoinPoint jp, MyAnno myAnnoAnnotation) {
        ...
        }
    }
    

    您可以在此处.

    这篇关于Aspect不从Scheduled捕获方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆