Main Tutorials

How to inject null value in Spring

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

1. Constructor Argument

The wrong way to inject a null into constructor argument, a really common mistake, and nice try 🙂


  <bean id="defaultMongoTypeMapper1"
	 class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper">
	 <constructor-arg name="typeKey" value="null" />
  </bean>

Correct way.


  <bean id="defaultMongoTypeMapper"
	class="org.springframework.data.mongodb.core.convert.DefaultMongoTypeMapper">
	<constructor-arg name="typeKey">
		<null />
	</constructor-arg>
  </bean>

2. Property

The wrong way to inject null value into property.


  <bean id="myConverter"
	class="com.mkyong.convert.MoneyConverter">
	<property name="typeMapper" value="null" />
  </bean>

Correct way.


  <bean id="myConverter"
	class="com.mkyong.convert.MoneyConverter">
	<property name="typeMapper"><null/></property>
  </bean>

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
7 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Chinmoy Anand
9 years ago

How to do using annotations

Dhruva Mist
10 years ago

wow! thank you! did not know if there are wrong and correct ways

gjbaxter
10 years ago

This works great for and style syntax. Any clue when using c: or p: namespaces?

Ravi Ch
10 years ago
Reply to  gjbaxter

Are u using Setter Injection then go for tag and are using constructor injection go for tag

Nishant
11 years ago

Hi, Pretty nice article. I have one question though.
The article explains the wrong way and correct way to pass null values, but it does not explain “why” a particular approach is wrong.
Why kind of issues I might face going with the wrong approach.
Basically, I want to understand why passing null as “null” is wrong.

Thanks!

Suman Shekhar
1 year ago
Reply to  Nishant

Actually it will start searching for a bean named null and we haven’t declared so it will give an error bean not found.

Also if you are using c schema you cannot write null or an empty string.

I have a question how to inject null values using c: schema ??

Dmitry
10 years ago
Reply to  Nishant

Nishant, because null is interpreted, as String with value “null”.