簡體   English   中英

Spring @Required注釋無法按預期工作

[英]Spring @Required annotation not working as expected

我正在嘗試測試Spring注釋,以查看它們如何與從Spring 3.0 Source派生的一些簡單示例一起工作(在本例中為“ @Required”注釋)。

首先,我提出了一個基本的“ Hello World”類型示例,該示例不使用任何注釋。 這可以按預期工作(即打印“ Hello Spring 3.0〜!”)。

然后,我在Spring3HelloWorld類中添加了一個DAO對象字段。 我的意圖是通過使用@Required注釋DAO的setter來故意導致異常發生,然后不對其進行設置。 但是,當我期望基於不遵循注釋“規則/要求”的異常時,出現空指針異常(因為this.dao為null)。

我以為我需要在從Spring3HelloWorld調用任何方法之前設置DAO對象,但是顯然不是這樣。 我認為我誤會了@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>

我的第一個猜測是,由於您使用的是XmlBeanFactory而不是推薦的ApplicationContext ,因此使用Spring和批注將不會獲得任何高級行為。

-編輯-

是的-請參閱此堆棧溢出問題/答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM