Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically load a spring xml file based on database values

We currently have a Spring web application and are doing our configuration using XML files. We are starting Spring the DispatcherServlet which creates an XmlWebApplicationContext and loads it from the default location: spring-servlet.xml.

I am specifying several additional configuration files using the context-param contextConfigLocation. This loads up our entire application from the XML files.

So here's what I want to do. The XML file contains the database connection information and our DAOs for accessing these tables. I want to use one of those DAOs to read a value from the database and load an additional set of beans from the XML file.

So if the database value retrieved is orange, I want to load beans from orange.xml. If it's apple, I want to load apple.xml. I want these beans to be part of the same application context so after they're loaded, I can move forward without noticing the difference.

I'm wondering if I should implement my own sub-class of XmlWebApplicationContext and have DispatcherServlet implement that, but I'm not quite sure how to proceed with that.

like image 257
Thom Avatar asked Feb 04 '26 08:02

Thom


1 Answers

Not exactly loading from the different files, but you can try to use Spring Environment and Profile abstractions.

<beans profile="apple">
    <bean id="someBean">
       ...first set of bean parameters...
    </bean>
</beans>
<beans profile="orange">
    <bean id="someBean">
       ...second set of bean parameters...
    </bean>
</beans>

And in java:

context.getEnvironment().setActiveProfiles("orange");
context.refresh();
like image 165
Losted Avatar answered Feb 09 '26 08:02

Losted