xl0e
xl0e

Reputation: 371

Spring: override parent bean

Is it possible to override/replace parent abstract bean?

E.G: 1st xml:

<bean id="inheritedTestBean" abstract="true" class="org.springframework.beans.TestBean">
</bean>

<bean id="inheritsWithDifferentClass" class="org.springframework.beans.DerivedTestBean" parent="inheritedTestBean">
</bean>

2nd xml

<bean id="inheritedTestBean2" abstract="true" class="org.springframework.beans.TestBean2">
</bean>
<alias name="inheritedTestBean2" alias="inheritedTestBean" />

TestBean2 inherits TestBean.

Upvotes: 3

Views: 2623

Answers (2)

Derrops
Derrops

Reputation: 8117

Even if you could do this, it would be very confusing. There is the @Primary annotation, you can take a look at that. Or you could take a look at spring profiles, so you have a default bean implementation, and then every other profile there is a different implementation for your abstract class.

Upvotes: 0

Ashwin Golani
Ashwin Golani

Reputation: 411

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.

Upvotes: 1

Related Questions