In this post we’ll see how to inject null and empty string values into constructor argument or property in Spring.
Injecting empty string in Spring
In Spring if you have to set any property to the empty String value then pass (“”) as a value for that property.
For example if you have an Employee bean and you want to set its email property to the empty String value (“”).
<bean id="employeeBean" class="com.knpcode.SpringProject.EmployeeBean"> <property name="email" value="" /> </bean>
If injected as a constructor argument-
<bean id="employeeBean" class="com.knpcode.SpringProject.EmployeeBean"> <constructor-arg name="email" value="" /> </bean>
Injecting null value in Spring
To inject null value into any property use the <null/> element. Keep in mind not to assign null as value=”null” as that would inject “null” as a String value, use <null/> element for null value.
<bean id="employeeBean" class="com.knpcode.SpringProject.EmployeeBean"> <property name="email"><null/></property> </bean>
If injected as a constructor argument-
<bean id="employeeBean" class="com.knpcode.SpringProject.EmployeeBean"> <constructor-arg name="email"><null/></constructor-arg> </bean>
Related Posts
- Injecting Prototype Bean into a Singleton Bean in Spring
- Spring Expression Language (SpEL) Tutorial
- Advantages and Disadvantages of Autowiring in Spring
- Spring IoC Container Types – ApplicationContext and BeanFactory
- Spring @Import Annotation
- Spring @PostConstruct and @PreDestroy Annotation
- Spring Boot Starters
- Create Java Project Using Maven in Eclipse
That’s all for the topic Injecting Null and Empty String Values in Spring. If something is missing or you have something to share about the topic please write a comment.
You may also like