1.扩展 org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource类
实现代码
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;public class DynamicDataSource extends AbstractRoutingDataSource { @Override protected Object determineCurrentLookupKey() { // TODO Auto-generated method stub return DbContextHolder.getDbType(); }}
2.实现一个线程安全的DbContextHolder类。
public class DbContextHolder { private static final ThreadLocal contextHolder = new ThreadLocal(); public static void setDbType(String dbType) { contextHolder.set(dbType); } /** * 取得dbtype类型 * @return */ public static String getDbType() { String str=(String) contextHolder.get(); if(null==str || "".equals(str)) str="1"; return str; } public static void clearDbType() { contextHolder.remove(); }}
3.修改spring的配置文件。
4.切换数据源方法。
在serverice方法之前调用
DbContextHolder.setDbType("2");表示使用第二个数据源。