2016-05-29 91 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> 

哪一個當然是比分開的文件更糟糕的解決方案,但它是唯一的方法,我可以使它工作。