如何使用一个DataSource以编程方式更改Spring中的数据库? [英] How to programatically change databases in Spring with one DataSource?
问题描述
我想看看在Spring中使用一个DataSources的最佳方法是什么,但能够在Java代码中切换数据库?下面是我的两个DataSource,它们转到相同的数据库服务器但是不同的数据库。
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:
一般的想法是路由DataSource充当中间
- 而'真正的'数据源可以在运行时根据查找键动态确定
。
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
这篇关于如何使用一个DataSource以编程方式更改Spring中的数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!