How to use the same bean in two different spring contexts?

I have two spring contexts and I need to use the same bean in both of them. Is there a way to share a bean between two contexts without making a parent context?

Upvotes: 1

Views: 1722

Answers (1)

gpeche
gpeche

Reputation: 22504

I don't think what you want is a good idea. If you have the same bean in two contexts, then which context manages the bean's lifecycle? By having a common parent owning the bean, you have a clear, unambiguous answer to that important question: the bean belongs to the parent context.

Now, if you know the beans will belong to context A and only want to bind them to some name in context B, I guess you could hack some kind of "guest" bean factory or whatever, that does something like:

Java:

public class GuestBeanFactory {
    private ApplicationContext guestBeanContext;

    @Inject
    public void setGuestBeanContext(ApplicationContext guestBeanContext) {
        this.guestBeanContext = guestBeanContext;
    }

    private String guestBeanName;

    @Inject
    public void setGuestBeanName(String guestBeanName) {
        this.guestBeanName = guestBeanName;
    }

    public Object getBean() {
        return guestBeanContext.getBean(guestBeanName);
    }
}

applicationContext.xml:

<beans ...>
    ...
    <bean id="myGuestFactory" class="GuestBeanFactory" scope="singleton">
        <property name="guestBeanContext" ref="...get a reference to the guest bean and inject it here" />
        <property name="guestBeanName" value="name-of-this-bean-inside-guestBeanContext"/>
    </bean>
    <bean id="myGuestBean" factory-bean="myGuestFactory" factory-method="getBean"/>
    ...
</beans>

This way, guestBeanContext manages name-of-this-bean-inside-guestBeanContext, but the "host" context can access that bean using the name myGuestBean.

Upvotes: 2

Related Questions