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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.