使用Spring AOP确认消息 - AspectJ

时间:2014-12-20 19:50:33

标签: spring aop aspectj

我正在尝试使用AspectJ学习Spring AOP实现。 我有5个不同包的课程。

package com.sample.a;
Class A{
    public void save(){
    }
    }
}

package com.sample.b;
Class B {
    public void save(){
    }
}

package com.sample.c;
Class C {
    public void save(){
    }
}

package com.sample.d;
Class D{
    public void save(){
    }
}

package com.sample.e;
Class E{
    public void save(){
    }
}

每当调用这些方法时,我需要打印“Hello World”,如何使用Spring AOP(AspectJ)实现上述场景。到目前为止,我已经做了以下事情 -

1)在applicationContext.xml中启用Spring AspectJ支持

<aop:aspectj-autoproxy />

2)在applicationContext.xml中定义了Aspect的引用

<bean id="sampleAspectJ" class="com.sample.xxxxxxxx" />

3)Aspect Class

/**
 * aspect class that contains after advice 
 */
package com.sample;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class SpringAopSample{

    @After(value = "execution(* com.sample.*.Save(..))")
    public void test(JoinPoint joinPoint) {


        System.out.println("Hello World");



    }

}

有没有更好的方法来实现上述方案?如果这5个类在不同的包中并且具有不同的方法名称怎么办?我是否需要在方面编写5种不同的方法(使用@after advice注释)

1 个答案:

答案 0 :(得分:2)

您应该熟悉AspectJ切入点语法。例如

  • 示例中您自己的切入点execution(* com.sample.*.Save(..))将与任何示例save()方法都不匹配,因为
    • 你用资本&#34; S&#34;写了Save(),但这些方法有小写&#34; s&#34;作为他们的第一个角色,
    • 您的课程宁愿与com.sample.*.*(子包!)匹配,而不仅仅是com.sample.*
  • 因此,您可以匹配子包类中的所有save()方法,如下所示:execution(* com.sample.*.*.save(..))。第一个*是子包ad,第二个*是类名。
  • 如果您希望将子包甚至类层次地匹配到任何深度,您可以使用..语法,如下所示:execution(* com.sample..save(..))
  • 如果您只希望在所有子包中匹配任何名称的public void个方法且没有参数,则可以使用execution(public void com.sample..*())

等等。我希望这可以回答你的问题,即使你还不清楚你想知道什么。

相关问题