我想將一個在Spring上下文中定義的bean注入CDI託管組件,但是我不成功。該bean沒有被注入,而是每次執行注入時創建一個新的實例。我的環境是JBoss Weld的Tomcat 7。使用CDI注入Spring bean @Inject
Spring的ApplicationContext是簡單明瞭:
<beans>
...
<bean id="testFromSpring" class="test.Test" />
...
</bean>
的CDI託管bean看起來是這樣的:
@javax.inject.Named("testA")
public class TestA {
@javax.inject.Inject
private Test myTest = null;
...
public Test getTest() {
return this.myTest;
}
}
這是我faces-config.xml
<faces-config xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd" version="2.0">
<application>
<el-resolver>org.springframework.web.jsf.el.SpringBeanFacesELResolver</el-resolver>
</application>
</faces-config>
然而,當我訪問test
來自JSF頁面的財產,新的每次訪問發生時都會創建實例。這是一個簡單的例子:
<html>
...
<p>1: <h:outputText value="#{testFromSpring}" /></p>
<p>2: <h:outputText value="#{testA.test}" /></p>
...
我得到以下輸出:
1: [email protected]
2: [email protected]
刷新後:
1: [email protected]
2: [email protected]
我可以看到第一個輸出是正確的。無論刷新頁面的頻率如何,testFromSpring
都會返回Spring上下文中定義的bean的值。然而,第二個輸出清楚地表明,每當test
組件的getTest
方法被調用時,就會創建一個新的Test
實例並注入,而不像我所期望的那樣使用Spring上下文中的實例。
那麼,這種行爲的原因是什麼?
如何從Spring上下文將bean注入到CDI託管bean中?
我也嘗試過使用使用Spring上下文定義的名稱限定詞,但現在拋出一個異常表示,該bean無法找到:
org.jboss.weld.exceptions.DeploymentException: WELD-001408 Injection point has unsatisfied dependencies. Injection point: field test.TestA.myTest; Qualifiers: [@javax.inject.Named(value=testFromSpring)]
的代碼
@javax.inject.Named("testA")
public class TestA {
@javax.inject.Inject
@javax.inject.Named("testFromSpring")
private Test myTest = null;
這可能是缺少咖啡的原因,但爲什麼要注入一個私人成員(已經設置爲空)。將myTest作爲TestA構造函數的一部分提供(例如構造函數注入)並不簡單嗎? – 2010-11-10 12:07:57
注入僅僅是一個例子,而不是問題的要點。 – perdian 2010-11-10 15:06:10