进样的BasicDataSource在弹簧
我使用Spring来访问数据库运行时:进样的BasicDataSource在弹簧
-
XML Spring上下文:
<bean id="ds" class="org.apache.commons.dbcp.BasicDataSource">...</bean> <bean id="jdbcTmp" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource" ref="ds" /> </bean> <bean id="myDao" class="MyDao"> <property name="jdbcTemplate" ref="jdbcTmp" /> </bean>
-
代码:
System.out.println("There is : " + new ClassPathXmlApplicationContext("beans.xml").getBean("myDao").countRowsInTheDB() + " rows in this source";
它很简单,而且效果很好。但是我想根据变量在运行时在不同的数据库中进行选择。
喜欢的东西:
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml"); int rows1 = ctx.getBean("myDao", "dataSource1").countRowsInTheDB(); int rows2 = ctx.getBean("myDao", "dataSource2").countRowsInTheDB();
什么是做到这一点的simpliest方式?
我希望为每个源的XML配置:
<bean id="myDao1" class="MyDao"><property name="data" ref="jdbcTmpForDataSource1" /></bean>
<bean id="myDao2" class="MyDao"><property name="data" ref="jdbcTmpForDataSource2" /></bean>
并编写代码:
int i = getDataSourceIndex();
ctx.getBean("myDao" + i).countRowsInTheDB();
创建第二个数据源,JDBC模板,道:
<bean id="ds2" class="org.apache.commons.dbcp.BasicDataSource">... </bean>
<bean id="jdbcTmp2" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds2" />
</bean>
<bean id="myDao2" class="MyDao">
<property name="jdbcTemplate" ref="jdbcTmp2" />
创建一个豆,这是所有的数据源的列表
在短短自动装配它,春天将注入名单
@Autowired List<DataSource> dataSources;
在您的代码遍历列表,并做蒙山的datasourceswhatever你想。