Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Beans - how to wire null as a constructor arg?

Tags:

java

spring

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!

like image 307
IAmYourFaja Avatar asked Oct 17 '12 19:10

IAmYourFaja


People also ask

Can beans be null?

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.

How pass null in Spring XML?

In Spring, you can uses this special <null /> tag to pass a “null” value into constructor argument or property.

Can we inject null?

In Spring dependency injection, we can inject null and empty values. In XML configuration, null value is injected using <null> element.

Can we inject null beans in Spring?

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.


2 Answers

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> 
like image 164
Reimeus Avatar answered Oct 02 '22 16:10

Reimeus


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> 
like image 27
Arham Avatar answered Oct 02 '22 15:10

Arham