DbContextHolder
public class DbContextHolder {
//线程安全的ThreadLocal
private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>();
public static void setDbType(String dbType) {
contextHolder.set(dbType);
}
public static String getDbType() {
return ((String)contextHolder.get());
}
public static void clearDbType() {
contextHolder.remove();
}
}
DynamicDataSource
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
public Object determineCurrentLookupKey() {
return DbContextHolder.getDbType();
}
}
spring.xml
<!-- 数据源属性配置文件 -->
<context:property-placeholder location="classpath:ibatis.properties" />
<bean id="jksh" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<!-- Connection Info -->
<property name="driverClassName" value="${driver.jksh}" />
<property name="url" value="${url.jksh}" />
<property name="username" value="${username.jksh}" />
<property name="password" value="${password.jksh}" />
<!-- Connection Pooling Info -->
<property name="maxIdle" value="${maxIdle.jksh}" />
<property name="maxActive" value="${maxActive.jksh}" />
<property name="defaultAutoCommit" value="false" />
<property name="timeBetweenEvictionRunsMillis"
value="${timeBetweenEvictionRunsMillis.jksh}" />
<property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis.jksh}" />
</bean>
<bean id="jclt" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<!-- Connection Info -->
<property name="driverClassName" value="${driver.jclt}" />
<property name="url" value="${url.jclt}" />
<property name="username" value="${username.jclt}" />
<property name="password" value="${password.jclt}" />
<!-- Connection Pooling Info -->
<property name="maxIdle" value="${maxIdle.jclt}" />
<property name="maxActive" value="${maxActive.jclt}" />
<property name="defaultAutoCommit" value="false" />
<property name="timeBetweenEvictionRunsMillis" value="${timeBetweenEvictionRunsMillis.jclt}" />
<property name="minEvictableIdleTimeMillis" value="${minEvictableIdleTimeMillis.jclt}" />
</bean>
<bean id="dataSource" class="com.jclt.service.commons.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="jksh" value-ref="jksh" /> <!--建议两个一样-->
<entry key="jclt" value-ref="jclt" />
</map>
</property>
<property name="defaultTargetDataSource" ref="jksh" /> <!--默认是<span style="font-family: Arial, 宋体;">jclt的数据源--></span><span style="font-family: Arial, 宋体;">
</span> </bean>
使用说明:
直接调用
DbContextHolder.setDbType("<span style="font-family: Arial, 宋体;">jclt</span><span style="font-family: Arial, 宋体;">");</span>
注意:
这个是静态方法可以调用,但是运用这个数据源再用另一个数据源时,切换没完成,页面可能就报错,我在控制层和service实现层都 加这个方法,发现在一个层加有时候还是会报错,实在不行就在dao那层也加上,建议是所有都加(我是没在找到办法,我哭啊,要是大家有什么办法私信我)。