2010-07-19 92 views
1

我想測試一下Spring註解,看看他們如何與來自Spring 3.0 Source得出一些簡單的例子(特別是在這種情況下,「@required」註釋)工作。春天@Required註解工作不正常

首先,我想出了一個不使用任何註釋的基本的「Hello World」式的例子。這按預期工作(即打印「Hello Spring 3.0〜!」)。

我然後加入一個DAO物場到Spring3HelloWorld類。我的目的是故意造成被標註爲DAO@Required的二傳手,但隨後沒有將其設定爲發生異常。但是,當我期待基於不遵循註解「規則/要求」的異常時,我得到空指針異常(因爲this.dao爲空)。

我以爲我需要設置DAO對象之前調用Spring3HelloWorld任何方法,但顯然情況並非如此。我假設我誤解了@Required的工作原理。

所以基本上我將如何得到下面給我一個錯誤線沿線的「嘿,你不能這樣做,你忘了設置DAO等等等等等等」。

Spring3HelloWorldTest.java:

import org.springframework.beans.factory.xml.XmlBeanFactory; 
import org.springframework.core.io.ClassPathResource; 

public class Spring3HelloWorldTest { 

    public static void main(String[] args) { 

     XmlBeanFactory beanFactory = new XmlBeanFactory(new ClassPathResource  ("SpringHelloWorld.xml")); 

     Spring3HelloWorld myBean = (Spring3HelloWorld) beanFactory.getBean("spring3HelloWorldBean"); 
     myBean.sayHello();   

    } 
} 

Spring3HelloWorld.java:

import org.springframework.beans.factory.annotation.Required; 

public class Spring3HelloWorld { 

    private DAO dao; 

    @Required 
    public void setDAO(DAO dao){ 
     this.dao = dao; 
    } 

    public void sayHello(){ 
     System.out.println("Hello Spring 3.0~!"); 

     //public field just for testing 
     this.dao.word = "BANANA!!!"; 
    } 
} 

SpringHelloWorld.xml:

<beans xmlns="http://www.springframework.org/schema/beans" 
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
     xmlns:context="http://www.springframework.org/schema/context" 
     xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-3.0.xsd"> 

    <context:annotation-config/> 

    <bean class="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/> 

    <bean id="dao" class="src.DAO" ></bean> 
    <bean id="spring3HelloWorldBean" class="src.Spring3HelloWorld" ></bean> 

</beans> 

回答

3

我的第一個猜測是,你不會得到任何高級因爲您使用的是XmlBeanFactory而不是r,所以會出現Spring和註釋行爲推薦ApplicationContext

- 編輯 -

燁 - 看到這個堆棧溢出question/answer

+0

啊我不知道這一點。謝謝,我一定會嘗試使用ApplicationContext。 – FromCanada 2010-07-19 20:53:27

+0

再次感謝。我測試了這兩種方法,他們都工作。 – FromCanada 2010-07-19 21:13:19

+0

+1好點... – skaffman 2010-07-20 07:28:18