Search code examples
javaspringspring-context

Merging two Spring Application Context without closing the first application context


In our application start-up, we are creating one application context having its own bean configuration xml. Then depending up on certain logic, we would need to dynamically load/import the second bean configuration into the existing application context.

One option is to close the existing application context and creating a new application context by importing both the bean definition xml files. But closing the application context takes time ( i.e destroying beans/executors etc ) , is there a way to merge both the application context without closing the existing one.


Solution

  • When using multiple application contexts you can achieve a hierarchy, which might be helpful here. You then first create the first instance, determine what to load next in a new instance with the first instance as a parent.

    Something like this

    ApplicationContext parent= new ClassPathXmlApplicationContext("your-context.xml");
    String nextXml = logicToDetermineXml();
    ApplicationContext toUse = new (new String[] {nextXml}, parent);
    

    Now you can use the one called toUse for the remainder of your application. Without having to recreate the whole context.