spring动态指定数据源
http://blog.163.com/wang_hj138@126/blog/static/140800106201263151242338/
目前很多项目中只能配置单个数据源,那么如果有多个数据源肿么办?Spring提供了一个抽象类AbstractRoutingDataSource,为我们很方便的解决了这个问题。
1.写一个DynamicDataSource类继承AbstractRoutingDataSource,并实现determineCurrentLookupKey方法
public class DynamicDataSource extends AbstractRoutingDataSource{
private final static Logger logger =LoggerFactory.getLogger("DynamicDataSource");
@Override
protected Object determineCurrentLookupKey(){
return DbContextHolder.getDbType();
}
}
2.写一个线程安全的ThreadLocal
public class DbContextHolder{
private static final ThreadLocal contextHolder =new ThreadLocal();
public static void setDbType(String dbType){
contextHolder.set(dbType);
}
public static String getDbType(){
return (String) contextHolder.get();
}
public static void clearDbType(){
contextHolder.remove();
}
}
3.dataSource的配置
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd" default-autowire="byName"> <bean id="aTestDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${a.jdbc.driverClassName}" /> <property name="url" value="${a.jdbc.url}" /> <property name="username" value="${a.jdbc.username}" /> <property name="password" value="${a.jdbc.password}" /> </bean> <bean id="bTestDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="${b.jdbc.driverClassName}" /> <property name="url" value="${gott.jdbc.url}" /> <property name="username" value="${b.jdbc.username}" /> <property name="password" value="${b.jdbc.password}" /> </bean> <bean id="dataSource" class="***.DynamicDataSource"> <property name="targetDataSources"> <map key-type="java.lang.String"> <entry key="aTestDataSource" value-ref="aTestDataSource" /> <entry key="bTestDataSource" value-ref="bTestDataSource" /> </map> </property> <property name="aTestDataSource" ref="aTestDataSource" /> </bean> </beans>
4.当需要切换数据源时,只要调用一行代码就可以了
DbContextHolder.setDbType("aTestDataSource");
当然有兴趣的朋友也可以用aop去自动切换数据源

浙公网安备 33010602011771号