我使用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();