2016-05-29 98 views
0

工作后,我有一个方面,在这个时刻没有做什么特别的东西:的Spring AOP之前和方法不使用XML配置

@Named 
public final class PreventNullReturn { 
    public void replaceNullWithSpecialCase() { 
     System.out.print("ASPECT CALLED!"); 
     throw new AssertionError(); 
    } 
} 

它只是应该抛出一个错误来证明它被调用。我有spring-aspects.xml文件,其中我宣布几个方面:

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:aop="http://www.springframework.org/schema/aop" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd" 
> 
    <aop:aspectj-autoproxy/> 

    <bean class="aspects.PreventNullReturn" 
      id="preventNullReturn" 
    ></bean> 

    <aop:config> 
     <aop:aspect 
       ref="preventNullReturn" 
     > 
      <aop:pointcut 
        id="preventNull" 
        expression="execution(* *.getById(..))" 
      ></aop:pointcut> 
      <aop:before 
        pointcut-ref="preventNull" 
        method="replaceNullWithSpecialCase" 
      ></aop:before> 
      <aop:after 
        pointcut-ref="preventNull" 
        method="replaceNullWithSpecialCase" 
      ></aop:after> 
     </aop:aspect> 
    </aop:config> 
</beans> 

而在春季单元测试我使用这种方式配置文件:

<import resource="classpath*:spring-aspects.xml" /> 

但一方面不叫。有趣的是,即使IDE显示Navigate to advised methods工具提示,它正确导航。我试图按照1.1.3. Applying aspects章节中的"Spring in Action, Fourth Edition book(这就是为什么我使用XML而不是类),但是我做错了什么,我无法弄清楚。如果我能提供更多有用的细节,请写信。如果您决定帮助我,请提前致谢,我将不胜感激。

回答

0

我发现我自己的答案,而不是导入它在配置文件中的资源春季单元测试:

<import resource="classpath*:spring-aspects.xml" /> 

我必须有它的配置文件内容直接春季单元测试:

<!--TODO: Move it to separated file--> 
<aop:aspectj-autoproxy/> 

<bean class="aspects.PreventNullReturn" 
     id="preventNullReturn" 
></bean> 

<aop:config> 
    <aop:aspect 
      ref="preventNullReturn" 
    > 
     <aop:pointcut 
       id="preventNull" 
       expression="execution(* *.getById(..))" 
     ></aop:pointcut> 
     <aop:before 
       pointcut-ref="preventNull" 
       method="replaceNullWithSpecialCase" 
     ></aop:before> 
     <aop:after 
       pointcut-ref="preventNull" 
       method="replaceNullWithSpecialCase" 
     ></aop:after> 
    </aop:aspect> 
</aop:config> 

哪一个当然是比分开的文件更糟糕的解决方案,但它是唯一的方法,我可以使它工作。