Java Aspectj 和捕获私有或内部方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4402009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 17:02:48  来源:igfitidea点击:

Aspectj and catching private or inner methods

javaspringaspectj

提问by awonline

I've configureg AspectJ with Spring and it works fine when "catching" public methods called from out of the class. Now I want do something like this:

我已经使用 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}

}

SomeLogic is a SpringBean. The methods innerA() and innerB() could be declared as private or public - the method someMethod() is called from a Struts action. Is it possible to catch with AspectJ the methods innerA() or innerB() called from someMethod() ?

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

My config (XML based):

我的配置(基于 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>

采纳答案by Espen

Yes it is easy to catch private methods with AspectJ.

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

An example that prints a sentence before all private methods:

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

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

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

If you are familiar with Eclipse, I recommend to develop AspectJ with STSor only install the AJDT plugin.

如果你熟悉 Eclipse,我建议你用STS开发 AspectJ或者只安装AJDT 插件

More information about Spring AOP capabilities can be found in the Spring reference documentation here.

可以在此处的 Spring 参考文档中找到有关 Spring AOP 功能的更多信息。