I have the following bean defined:
<bean id="myBean" class="com.me.myapp.Widget"> <constructor-arg name="fizz" value="null"/> <constructor-arg name="buzz" ref="someOtherBean" /> </bean>
When I run my app, Spring throws a bean config exception:
[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
I just want to create a Widget
like I would if I wrote the following Java:
Widget w = new Widget(null, someOtherBean);
How can I do this? Thanks in advance!
Internal representation of a null bean instance, e.g. for a null value returned from FactoryBean. getObject() or from a factory method. Each such null bean is represented by a dedicated NullBean instance which are not equal to each other, uniquely differentiating each bean as returned from all variants of BeanFactory.
In Spring, you can uses this special <null /> tag to pass a “null” value into constructor argument or property.
In Spring dependency injection, we can inject null and empty values. In XML configuration, null value is injected using <null> element.
If you need to inject null value for any field in Spring then use the special <null/> element for it, don't use value=”null” because that will pass "null" as a String value. Use <null/> element instead in your Spring configuration.
You can use Spring's <null>
tag:
<bean id="myBean" class="com.me.myapp.Widget"> <constructor-arg name="fizz"> <null /> </constructor-arg> <constructor-arg name="buzz" ref="someOtherBean" /> </bean>
At times spring fails to inject the values in the ordered you have mentioned into a constructor. It's better if you try with explicit ordering, i.e.
<constructor-arg index="0" name="fizz"><null/></constructor-arg> <constructor-arg index="1" name="buzz"><ref bean="someOtherBean"/></constructor-arg>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With