Aspectj和捕获私有或内部方法

awo*_*ine 6 java spring aspectj

我使用Spring配置AspectJ,并且在"捕获"从类外调用的公共方法时它工作正常.现在我想做这样的事情:

public class SomeLogic(){

   public boolean someMethod(boolean test){

      if(test){
        return innerA();
      } else {
        return innerB();
      }
   }


   private boolean innerA() {// some logic}
   private boolean innerA() {// some other logic}

}
Run Code Online (Sandbox Code Playgroud)

SomeLogic是一个SpringBean.方法innerA()和innerB()可以声明为private或public - 从Struts动作调用someMethod()方法.是否有可能从AspectJ中捕获从someMethod()调用的方法innerA()或innerB()?

我的配置(基于XML):

    <aop:aspect id="innerAAspect" ref="INNER_A">
        <aop:pointcut id="innerAService" expression="execution(* some.package.SomeLogic.innerA(..))"/>
    </aop:aspect>

    <aop:aspect id="innerAAround" ref="INNER_A">
        <aop:around pointcut-ref="innerAService" method="proceed"/>
    </aop:aspect>


    <aop:aspect id="innerBAspect" ref="INNER_B">
        <aop:pointcut id="innerBService" expression="execution(* some.package.SomeLogic.innerB(..))"/>
    </aop:aspect>

    <aop:aspect id="innerBAround" ref="INNER_B">
        <aop:around pointcut-ref="innerBService" method="proceed"/>
    </aop:aspect>
Run Code Online (Sandbox Code Playgroud)

Esp*_*pen 5

是的,使用AspectJ很容易捕获私有方法.

在所有私有方法之前打印句子的示例:

 @Pointcut("execution(private * *(..))")
 public void anyPrivateMethod() {}

 @Before("anyPrivateMethod()")
 public void beforePrivateMethod(JoinPoint jp) {
     System.out.println("Before a private method...");
 }
Run Code Online (Sandbox Code Playgroud)

如果您熟悉Eclipse,我建议使用STS开发AspectJ 或仅安装AJDT插件.

关于Spring AOP的功能的更多信息可以在Spring参考文档中找到这里.

  • 它是.Spring AOP使用代理对象或CGLIB,这些替代方案都不支持它.这就是Spring方面也支持AspectJ的原因. (2认同)
  • 是的。但是您需要调整您的构建过程,以便有一个步骤将 AspectJ 方面融入到代码中。与 Spring AOP 相比,AspectJ AOP 不是基于代理的。 (2认同)