How to Inject Null or Blank values to a Spring Bean


To inject an NULL value which is equivalent to bean.setMessage(null):

<bean id=”beanId” class=”bean”>
<property name=”message”><null/></property>
</bean>

To inject an empty Stringe which is equivalent to bean.setMessage(“”)

<bean id=”beanId” class=”bean”>
<property name=”message” value=””></property>
</bean>

 

Is it mandatory to have the “id” property in Bean/ApplicationContext Xml


Typical Bean Configuration XML file is given below.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd" >

<bean class="com.malliktalksjava.service.EmployeeService">
    <property name="empRepository" ref="employeeDAO"/>
</bean>

<bean id="employeeDAO" class="com.malliktalksjava.dao.EmployeeDao"/>

</beans>

From the above config, EmployeeService Bean is Anonymous because no id is supplied explicitly. Hence, Spring Container generates a unique id for that bean. It uses the fully qualified class name and appends a number to it.

However, if you want to refer that bean by name, through the use of the ref element you must provide a name.

Right way of doing is shown using second Bean, its been declared with employeeDAO id attribute in order to be referenced by the empRepository property of the first Bean.