Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining the same Spring bean twice with same name

Is having two definition for a bean (with same name and class) valid in Spring IOC ?

I am having two bean definition files included in web.xml. See the sample below.

applicationContext-beans1.xml

<bean name="myWao"     class="com.beans.myBean">        </bean>  

applicationContext-beans2.xml

<bean name="myWao"     class="com.beans.myBean">        </bean>  

I am not facing any issue till now. But, will this possibly impact in the real environment which will be multi threaded and clustered ?

Note: Both the XMLs are loaded as I am able to use the other beans defined(only once) in both the XMLs

like image 874
hop Avatar asked Jun 12 '12 08:06

hop


People also ask

Can we define two beans with same name in Spring?

Spring beans are identified by their names within an ApplicationContext. Therefore, bean overriding is a default behavior that happens when we define a bean within an ApplicationContext that has the same name as another bean. It works by simply replacing the former bean in case of a name conflict.

Can we have two beans with same class name?

If you define two beans of same class, without different bean id or qualifiers ( identifier) , Spring container will not be able to understand which bean to be loaded , if you try to access the bean by passing the classname and you will get NoUniqueBeanDefinitionException as there are two qualifying TestBean.

Which annotation is used for Autowiring when you have 2 beans with same name?

There's another annotation called @Primary that we can use to decide which bean to inject when ambiguity is present regarding dependency injection. This annotation defines a preference when multiple beans of the same type are present.

Can I have 2 bean definition of a class with singleton scope?

It will throw an error at runtime, as you can not define two Sspring beans of the same class with Singleton Scope in XML.


1 Answers

It's valid, but you'll find that one bean is overridden by the other. You'll see this in the logs as

Overriding bean definition for... 

This behaviour allows you to override previously supplied bean definitions. It affects the static assembly of your app, and doesn't relate to threading/clustering as suggested in your question.

Note that the DefaultListableBeanFactory allows you to configure this behaviour via setAllowBeanDefinitionOverriding()

like image 93
Brian Agnew Avatar answered Oct 06 '22 01:10

Brian Agnew