Spring – BeanId vs. BeanName

Spring supports two ways to adress a Bean, by ID or by Name.
But what happens in the following scenario :

<bean id="test1" name="test" class="java.lang.String"/>
<bean id="test" class="java.lang.Object"/>

If the declaration is made in one spring configuration xml, the spring parser will throw an exception during spring startup. This is expected.

But be careful if the declaration is distributed over two spring configuration files. In this scenario the spring parser will not intervene.
If you try to get the bean via applicationContext.getBean(“test”), the id=test1 bean is delivered. In general it’s better to declare beans by id not by name. This avoids to corrupt beanDefinitions in other spring configuration files.

The name property should only be used for names which datatypes are not xsd:ID conform.

Leave a Reply

Your email address will not be published. Required fields are marked *

*