原帖地址:http://bbs.csdn.net/topics/320191834
一、首先在spring配置文件中做如下配置:
<pre name="code" class="html"><bean id="dataSource" class="com.ickes.common.utils.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="0" value-ref="dataSource1" />
<entry key="1" value-ref="dataSource2" />
</map>
</property>
<property name="defaultTargetDataSource" ref="dataSource1" />
</bean>
dataSource1和dataSource2是两个自定义的数据源。
二、编写工具类
类1:
<pre name="code" class="java">import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DbContextHolder.getDbType();
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
}
类2:
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();
}
}
三、dao调用
public PageBean<CapEventProl> getCapEvents(String tableDate,Integer pageNo,
Integer pageSize, String sqlWhere, Object[] params) {
String sql=" select * from dual";
if(StringUtils.isNotBlank(sqlWhere)){
sql += sqlWhere;
}
//选择数据源
DbContextHolder dh=new DbContextHolder();
dh.setDbType("1");
//System.out.println(sql);
return searchPaginate(pageNo, pageSize, sql, params, CapEventProl.class);
}