2012-01-01 27 views
0

我幾乎是Spring的初學者,所以不要以爲我沒有提到我可能做過的事情。無法獲得Spring依賴注入工作

我試圖讓依賴注入的工作,我有以下內容的spring.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:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.1.xsd"> 

<context:annotation-config/> 
<bean id="connection" class="richo.project.ConnectionImpl"/> 
</beans> 

,然後在我的代碼有:

private IConnection conn; 
@Resource(name="connection") 
public void setConn(IConnection conn){ 
this.conn = conn; 
} 

當我嘗試在我的代碼中使用conn對象我得到一個nullpointerexception

請記住,我實際上並不知道如果彈簧運行,我使用IntelliJ,它放置了13個與彈簧相關的jar文件在我的lib目錄中,但我無法確定Spring是否嘗試注入任何東西

回答

2

只要在你的類路徑中有Spring是不足以使這項工作。

必須要求Spring產生你需要的對象,以便對任何註解進行優化。這種情況發生在Spring容器中,但是對於獨立應用程序,您需要有一個Spring上下文(例如AnnotationConfigApplicationContext)並通過它的getBean()方法詢問它。

+0

因此,類中的註釋只有在Spring實例化時纔有效,這意味着如果我僅僅使用新的,spring將會沒有閱讀這些註釋? – Richo 2012-01-01 13:48:16

+0

Guice的確如此。我不確定Spring是否屬於這種情況(關於_how_很多classloader魔術的問題已經到位)。 – 2012-01-01 13:50:59

+1

@Richo:是的,Spring只注入它創建的bean。你實例化自己的豆不會被注入。 – 2012-01-01 13:54:29

0

首先,您的代碼無法編譯。應該堅持JavaBean規範,因此該方法應該是

public void setConn(IConnection conn){ 
    this.conn = conn; 
} 

現在,僅僅因爲你有一個春天的XML文件,並在類路徑中春瓶不作春神奇運行,並注入依賴。您需要加載應用程序上下文,並從此上下文中加載至少一個bean。這個bean將遞歸地注入所有的依賴項。

查看http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/htmlsingle/spring-framework-reference.html#beans-factory-instantiation爲例。

+0

如果你指的是「voidSetConn」,那麼這是一個錯字,我已經在我的問題中糾正 – Richo 2012-01-01 13:49:39