如何在Spring中使用一个DataSource以编程方式更改数据库? [英] How to programmatically change databases in Spring with one DataSource?
问题描述
我正在寻找在Spring中使用一个DataSources但能够从Java代码中切换数据库的最佳方法是什么?以下是我的两个数据源,它们分别位于相同的数据库服务器但位于不同的数据库中.
I'm looking to see what's the best way to use one DataSources in Spring but be able to switch the database from within the Java code? Below are my two DataSources and they go to the same database server but different databases.
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.sybase.jdbc3.jdbc.SybDataSource" />
<property name="url"
value="jdbc:sybase:Tds:10.20.30.40:50/DATABASE_EMS" />
<property name="username" value="userid" />
<property name="password" value="derp" />
</bean>
<bean id="dataSourceMain" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="com.sybase.jdbc3.jdbc.SybDataSource" />
<property name="url"
value="jdbc:sybase:Tds:10.20.30.40:50/DATABASE" />
<property name="username" value="userid" />
<property name="password" value="derp" />
</bean>
我将它们绑定到各自的bean,但我正在查看我的旧代码,用2个单独的bean实现它非常尴尬.是否有关于在需要时如何使用一个DataSource和切换数据库的想法/想法?
I have them bound to their own respective bean but I'm looking at my legacy code and it's going to be VERY awkward to implement this with 2 separate beans. Is there any ideas/thoughts on how to be able to use one DataSource and switch databases when I need to?
推荐答案
您可以通过扩展Spring的AbstractRoutingDataSource
并将现有的数据源包装在其中来实现.有关详细信息,请查看本文.引用该文章:
You can do this by extending the Spring's AbstractRoutingDataSource
and wrapping your existing data sources in it. Check this article for details. Quoting from the article:
一般的想法是路由数据源充当中介 –虽然可以在运行时动态确定真实"数据源 基于查找键.
The general idea is that a routing DataSource acts as an intermediary – while the 'real' DataSource can be determined dynamically at runtime based upon a lookup key.
也可以在SO上看到类似的问题:
Also see similar questions on SO:
- Using AbstractRoutingDataSource to dynamically change the database schema/catalog
- Reading from multiple Db's with same Persistence Unit?
- How to create Dynamic connections (datasource) in spring using JDBC
这篇关于如何在Spring中使用一个DataSource以编程方式更改数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!