2012-10-17 20 views
35

我有以下的bean定義:Spring Beans - 如何將null作爲構造函數arg?

<bean id="myBean" class="com.me.myapp.Widget"> 
    <constructor-arg name="fizz" value="null"/> 
    <constructor-arg name="buzz" ref="someOtherBean" /> 
</bean> 

當我運行我的應用程序,春拋出一個bean配置例外:

[java] Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myBean' defined in class path resource [spring-config.xml]: 
Unsatisfied dependency expressed through constructor argument with index 0 
of type [com.me.myapp.Widget]: Could not convert constructor argument value of 
type [java.lang.String] to required type [com.me.myapp.Widget]: Failed to 
convert value of type 'java.lang.String' to required type 
'com.me.myapp.Widget'; nested exception is java.lang.IllegalStateException: 
Cannot convert value of type [java.lang.String] to required 
type [com.me.myapp.Widget]: no matching editors or conversion strategy found 

我只是想創建一個Widget像我想如果我寫的以下Java:

Widget w = new Widget(null, someOtherBean); 

我該怎麼做?提前致謝!

回答

74

你可以使用Spring的<null>標籤:

<bean id="myBean" class="com.me.myapp.Widget"> 
    <constructor-arg name="fizz"> 
      <null /> 
    </constructor-arg> 
    <constructor-arg name="buzz" ref="someOtherBean" /> 
</bean> 
2

有時春天失敗在你所提到的成構造有序注入值。這是更好,如果你有明確的排序嘗試,即

<constructor-arg index="0" name="fizz"><null/></constructor-arg> 
<constructor-arg index="1" name="buzz"><ref bean="someOtherBean"/></constructor-arg> 
0

這是,實際上,不是爲我工作,

所以我所做的就是,經過春, 的對象,但問:「如果對象爲空」,並創建新的對象,然後將其分配給它,

它也做一次(類似於彈簧), 的不同之處在於,它不是最佳實踐,對象的創建點在班級的流動,而不是在早期階段。

相關問題