从Spring中已建议的方法触发第二个建议的方法

从Spring中已建议的方法触发第二个建议的方法,spring,aop,Spring,Aop,我有一个类,称之为X,在这个类中,我成功地建议一个方法从带注释的Spring调用它method(){} 这就是: public class X { public void method(){...} public void method2(){...} } 当然,这是我的观点: @Aspect public class MyAspect{ @Pointcut("execution(* X.method(..))") public void methodJP(){

我有一个类,称之为X,在这个类中,我成功地建议一个方法从带注释的Spring调用它method(){}

这就是:

public class X {
    public void method(){...}
    public void method2(){...}
}
当然,这是我的观点:

@Aspect
public class MyAspect{
    @Pointcut("execution(* X.method(..))")
    public void methodJP(){}

    @Pointcut("execution(* X.method2(..))")
    public void method2JP(){}

    @Around("methodJP()")
    public void doMethodJP(ProceedingJoinPoint pjp) throws Exception {
        pjp.proceed(); //Amongst other things!!!
    }

    @After("method2JP()")
    public void doMethod2JP(JoinPoint jp) throws Exception {
        //Do some stuff here
    }
}
现在。。。这两个连接点都工作得很好,但是,在我的X.method中,我还调用method2JP()建议的方法。。。当然,我的method2JP不会被触发

有什么办法可以让它工作吗


谢谢。

methodJP()
应该在另一个类中声明。在常规场景中,当您从同一对象内调用方法时,不会触发方面。

由于Spring AOP通过代理类工作,因此要调用通知,必须通过bean工厂提供的代理或包装器调用该方法

如果不想分成多个类,可以让该方法从beanfactory检索“自身”的代理版本。像这样的

@Service
public class MyService {
    @Autowired
    ApplicationContext context;

    public void method1() {
        context.getBean(MyService.class).method2();
    }

    public void method2() {
    }

}

这将保证从method1调用method2将应用method2切入点的任何方面。

谢谢,我担心是这样的。我喜欢它。。。让我来“旋转”一下!是的,完全是犹太人区。更重要的是,它打破了AOP的整个概念,因为它迫使您修改您建议的代码。它是有效的(我自己也曾多次使用过这个“hack”),但将第二种方法分解成另一个bean可能更为优雅。这是内聚/分裂和符合Springs限制之间的平衡。但是就像有人说的,如果它有效,它是美丽的。。。