Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring's overriding bean

Tags:

spring

Can we have duplicate names for the same bean id that is mentioned in the XML? If not, then how do we override the bean in Spring?

like image 565
gaurav Avatar asked May 01 '11 15:05

gaurav


People also ask

How do you override beans?

Bean Overriding 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 override bean?

@Buchi Yes, it is allowed. Bean from the file read later in sequence will override entirely previous definition which won't be instantiated at all.

How do I bypass Spring configuration?

To make a configuration in Spring Boot, you need to create a class and annotate it with @Configuration . Usually, in the configuration class, you can define a beans object. But if you want to override built-in configuration, you need to create a new class that extends the built-in class.


2 Answers

Any given Spring context can only have one bean for any given id or name. In the case of the XML id attribute, this is enforced by the schema validation. In the case of the name attribute, this is enforced by Spring's logic.

However, if a context is constructed from two different XML descriptor files, and an id is used by both files, then one will "override" the other. The exact behaviour depends on the ordering of the files when they get loaded by the context.

So while it's possible, it's not recommended. It's error-prone and fragile, and you'll get no help from Spring if you change the ID of one but not the other.

like image 196
skaffman Avatar answered Sep 19 '22 05:09

skaffman


I will add that if your need is just to override a property used by your bean, the id approach works too like skaffman explained :

In your first called XML configuration file :

   <bean id="myBeanId" class="com.blabla">        <property name="myList" ref="myList"/>    </bean>     <util:list id="myList">        <value>3</value>        <value>4</value>    </util:list> 

In your second called XML configuration file :

   <util:list id="myList">        <value>6</value>    </util:list> 

Then your bean "myBeanId" will be instantiated with a "myList" property of one element which is 6.

like image 25
lboix Avatar answered Sep 21 '22 05:09

lboix