Adding a Pre-constructed Bean to a Spring Application Context

后端 未结 6 1911
醉话见心
醉话见心 2020-12-24 02:24

I am writing a class that implements the following method:

public void run(javax.sql.DataSource dataSource);

Within this method, I wish to

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-24 03:16

    I have been in the exact same situation. As nobody proposed my solution (and I think my solution is more elegant), I will add it here for future generations :-)

    The solution consists of two steps:

    1. create parent ApplicationContext and register your existing bean in it.
    2. create child ApplicationContext (pass in parent context) and load beans from XML file

    Step #1:

    //create parent BeanFactory
    DefaultListableBeanFactory parentBeanFactory = new DefaultListableBeanFactory();
    //register your pre-fabricated object in it
    parentBeanFactory.registerSingleton("dataSource", dataSource);
    //wrap BeanFactory inside ApplicationContext
    GenericApplicationContext parentContext = 
            new GenericApplicationContext(parentBeanFactory);
    parentContext.refresh(); //as suggested "itzgeoff", to overcome a warning about events
    

    Step #2:

    //create your "child" ApplicationContext that contains the beans from "beans.xml"
    //note that we are passing previously made parent ApplicationContext as parent
    ApplicationContext context = new ClassPathXmlApplicationContext(
            new String[] {"beans.xml"}, parentContext);
    

提交回复
热议问题