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?
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.
@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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With