Announcement Announcement Module
No announcement yet.
Overriding a Bean definition Page Title Module
Move Remove Collapse
Conversation Detail Module
  • Filter
  • Time
  • Show
Clear All
new posts

  • Overriding a Bean definition


    I tried to search for the answer, but didn't find Trying it out here.

    I have a XMLBeanFactory (A) used for some purpose, and then I have another XMLBeanFactory (B) used in a different context. For some reason, I would like to read a Bean definition from Factory B, and place the same definition, at the same key in Factory (A) (with the problem that my singleton in factory (A) may have already been created).

    I didn't find a way to do this, even by reading the Bean definition in (B) and using the registerBeanDefinition(beanName, beanDefinition) method on (A).

    Is this possible to do it ?

    Thanks a lot

  • #2
    You can share a bean instance between two XmlBeanFactory by using a parent XmlBeanFactory:
    - P (parent XmlBeanFactory): contains the shared bean you want to use in A and B
    - A: remove definition of your shared bean
    - B: remove definition of your shared bean

    When you instanciate A and B, provide P as the value of parameter parentBeanFactory

      XmlBeanFactory p = new XmlBeanFactory(isP);
      XmlBeanFactory a = new XmlBeanFactory(isA, p);
      XmlBeanFactory b = new XmlBeanFactory(isB, p);
    XmlBeanFactory A and B will inherits your shared bean definition / instance from P.



    • #3
      Note also that ContextLoader is set up so that it may be easily subclassed to provide a parent to the main web application context that is normally created by itself. This allows you for example to use something like a SingletonBeanFactoryLocator to instantiate the 'main' application context(s), and then the web one is just a child of it.


      • #4
        Thank you both for your answers,

        Yes I knew about the parent factory, but my case is different. In fact, I really want at some point to change the behaviour of a Factory. In fact override its definition. Maybe the logic is wrong to do such a thing.

        But its true, that it is at least interesting, technically speaking, to know if it is possible to do it....


        • #5
          You can use HotSwappableTargetSource. You have to call swap() method whenever you want to swap the implemenation.

          I'm assuming both your beans implement a common interface.