Spring配置多数据源
- - ITeye博客首先在配置文件中配置多个dataSource. 扩展Spring的AbstractRoutingDataSource抽象类,实现动态数据源. AbstractRoutingDataSource中的抽象方法determineCurrentLookupKey是实现数据源的route的核心.这里对该方法进行Override.
public class DynamicDataSource extends AbstractRoutingDataSource{ @Override protected Object determineCurrentLookupKey() { return DBContextHolder.getDBType(); } }
public class DBContextHolder{ public static final String DATA_SOURCE_FROM = "dataSourceFrom"; public static final String DATA_SOURCE_TO = "dataSourceTo"; private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>(); public static void setDBType(String dbType) { contextHolder.set(dbType); } public static String getDBType() { return contextHolder.get(); } public static void clearDBType() { contextHolder.remove(); } }
<bean id="dynamicDataSource" class="datasource.DynamicDataSource" > <!-- 通过key-value的形式来关联数据源 --> <property name="targetDataSources"> <map> <entry value-ref="dataSourceFrom" key="dataSourceFrom"></entry> <entry value-ref="dataSourceTo" key="dataSourceTo"></entry> </map> </property> <property name="defaultTargetDataSource" ref="dataSourceFrom" /> </bean>
<!-- JdbcTemplate使用动态数据源的配置 --> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> <property name="dataSource"> <ref bean="dynamicDataSource" /> </property> </bean> <!-- 对JdbcTemplate的应用封装类 --> <bean id="sqlBaseDAO" class="com.whty.dao.BaseDAOImpl"> <property name="jdbcTemplate"> <ref bean="jdbcTemplate" /> </property> </bean>5. 动态数据源的管理
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); BaseDAO dao = (BaseDAO) context.getBean("sqlBaseDAO", BaseDAOImpl.class); try { DBContextHolder.setCustomerType(DBContextHolder.DATA_SOURCE_FROM); System.err.println(dao.select("select count(*) sum from TEST t ").get(0).get("SUM")); DBContextHolder.setCustomerType(DBContextHolder.DATA_SOURCE_TO); System.err.println(dao.select("select count(*) sum from TEST t ").get(0).get("SUM")); } catch (Exception e) { e.printStackTrace(); }如果在service层有比较统一的规则的话,也可以使用aop设置数据源使用。
DBContextHolder.clearDBType();清空数据源信息。