Spring Beans - 如何将 null 作为构造函数 arg?

2022-08-31 23:57:04

我定义了以下豆子:

<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

我只想创建一个像我写下面的Java一样:Widget

Widget w = new Widget(null, someOtherBean);

我该怎么做?提前致谢!


答案 1

您可以使用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

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

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

推荐