Spring AspectJ Style AOP

时间:2011-03-15 21:24:09

标签: java spring aop aspectj

我有一个使用Spring的Java应用程序,我有方面

@Aspect
public class MyAspect
{

    @Pointcut("execution (* com.mycompany.MyClass.*(..))")
    public void doStuff() {}

    @Around("doStuff()")
    public Object aroundDoStuff(ProceedingJoinPoint pjp) throws Throwable
    {
        System.out.println("before doStuff);
      try
      {
        return pjp.proceed();
      }
      finally
      {
        System.out.println("after doStuff");
      }
  }
}

然后我的spring bean文件有

<aop:aspectj-autoproxy proxy-target-class="true" />
<bean id="MyAspect"
    class="com.mycompany.MyAspect" />

现在我希望MyClass中的所有方法都能通过上面的切入点匹配,但似乎并非如此(只有一种方法似乎应用了建议)。我不确定这是否与我代理课程的事实有关,但有人看到我在这里做错了吗?

编辑:从主类调用代码,执行以下操作:

ApplicationContext cxt; // lookup the cxt
MyClass mc = (MyClass) cxt.getBean("MyClassBean");
mc.doSomething(); // I expect the advice to be applied here.

感谢, 杰夫

2 个答案:

答案 0 :(得分:1)

原来这个问题是因为我代理的是一个类,而不是一个接口。我需要更改切入点以匹配实现接口的所有类,然后使用target切入点过滤到MyClass。

编辑:添加详细信息......

如果MyClass扩展了AbstractMyClass并实现了MyInterface,我希望建议MyInterface中的所有方法,但事实并非如此。我错误地将我的切入点声明为:

@Pointcut(execution(* com.mycompany.MyClass.methodInAbstract()))

将其更改为

@Pointcut(execution(* com.mycompany.MyInterface.methodInAbstract()) && target(com.mycompany.MyClass))

运作良好。

答案 1 :(得分:0)

您的CLASSPATH中可能没有cglib,这是因为当您指定proxy-target-class = true时,会创建基于CGLIB的代理,而不是基于默认的基于Java动态代理的代理。您可以在路径中尝试使用CGLIB,还是删除proxy-target-class属性(假设您的bean确实具有动态代理工作所需的接口)。

编辑1:我尝试了你的样本,并把它放在github的这个位置 - git://github.com/bijukunjummen/mvc-samples.git,你可以执行测试来运用你的场景 - {{ 1}}它似乎运作良好。能否请您查看此测试,看看它与您的案例有何不同。