45

我定义了以下bean:

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

当我运行我的应用程序时,Spring 抛出一个 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);

我怎样才能做到这一点?提前致谢!

4

3 回答 3

89

您可以使用 Spring 的<null>标签:

<bean id="myBean" class="com.me.myapp.Widget">
    <constructor-arg name="fizz">
            <null />
    </constructor-arg>
    <constructor-arg name="buzz" ref="someOtherBean" />
</bean>
于 2012-10-17T19:36:09.883 回答
3

有时 spring 无法将您提到的顺序中的值注入到构造函数中。如果您尝试使用显式排序会更好,即

<constructor-arg index="0" name="fizz"><null/></constructor-arg> 
<constructor-arg index="1" name="buzz"><ref bean="someOtherBean"/></constructor-arg>
于 2012-10-17T19:39:46.200 回答
0

this was, actually, not working for me,

so what I've done is, not passing the object through spring, but asking "if the object is null", and create New object and assign it to it,

it is also done once (similar to spring), the difference is that, it is not the best practice, and the creation point of the object is in the flow of the class, and not in early stage.

于 2013-04-28T15:30:57.810 回答