Reputation: 729
I am developing an application where I need to specify different datasources depending on the circumstances. I want to use one database when the application is being tested and one for production. Something like specifying the driver class and login details via a property's file or an evironment variable. Currently I have to change the details then restart the app. Is there a way to change these properties dynamically without restarting the application?.
Upvotes: 1
Views: 2059
Reputation: 53516
You can use the resource tag + Spring's system property place holder like so...
<import resource="/resources/myDataSourceBeans-${runtime.environment}.xml"/>
All you need to do is put /resources/myDataSourceBeans-prod.xml
and /resources/myDataSourceBeans-test.xml
into the project's classpath with the proper datasource beans and define a system property called runtime.environment
and set it equal to either test
or prod
.
After checking my sources I found this blog entry which might help you out too.
[update] I just realized that you requested runtime changes. My answer is only really for environment sepration which is usually good enough as you shouldn't hit production datasources from a non production system.
Upvotes: 2
Reputation: 41126
Using JNDI data sources.
Referred from Spring in Action:
Spring applications will quite often be deployed to run within a JEE application server such as WebSphere, JBoss, or even a web container like Tomcat. These servers allow you to configure data sources to be retrieved via JNDI. The benefit of configuring data sources in this way is that they can be managed completely external to the application, leaving the application to simply ask for a data source when it’s ready to access the database. Moreover, data sources managed in an application server are often pooled for greater performance and can be hot-swapped by system administrators.
Sample applicationContext-dataSource.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jee="http://www.springframework.org/schema/jee"
xsi:schemaLocation=" http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">
<!-- D A T A S O U R C E S -->
<jee:jndi-lookup id="dataSource"
jndi-name="jdbc/myDatasource"
resource-ref="true" />
</beans>
Hope this helps.
Upvotes: 2
Reputation: 20614
If you really wont to change on runtime (which is very uncommon for the reason of a test/production switch) you can use a DelegatingDataSource an change the target to one or another without modifying all dependent beans.
Upvotes: 1