Search code examples
javaspringspring-bootdependency-injectionoverriding

Override spring bean without an alias that is also the parent


I have a bean in module1-spring.xml-

<bean id="parent" class="com.Parent"/>

<bean id="service" class="com.Service">
    <property name="parent" ref="parent"/>
</bean>

I want to override the bean in module2-spring.xml-

<bean id="child" class="com.Child" parent="parent"/>

I want child to be passed in service instead of parent. If I alias child as parent i.e.

<alias id="child" alias="parent"/>

then the parent attribute will read child instead of parent bean and fail on server startup with error-

BeanDefinitionStoreException: Invalid bean definition with name 'child' defined in class path resource [module2-spring.xml]: Could not resolve parent bean definition 'parent'.

What is the correct way of overriding parent while its also the parent of child?


Solution

  • Copying the service bean in module2 and injecting child fixed the issue.
    module2-spring.xml-

    <bean id="service" class="com.Service">
        <property name="parent" ref="child"/>
    </bean>