我需要在action处理业务的时候切换数据源,但始终选择的是缺省的数据源,切换失败
applicationContext.xml配置
class="org.logicalcobwebs.proxool.ProxoolDataSource">
${jdbc.driverClassName}
value="${pool.maxPoolSize}" />
value="${pool.minPoolSize}" />
${jdbc.url.ss}
.....
<bean id="dataSource1" parent="parentDataSource">
<property name="driverUrl">
<value>${jdbc.url.gy}</value>
</property>
</bean>
<bean id="dynamicDatasource"
class="com.gtd.rocket.common.util.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="ss" value-ref="ssDataSource"></entry>
<entry key="sf" value-ref="sfDataSource"></entry>
<entry key="dlc" value-ref="dlcDataSource"></entry>
<entry key="jz" value-ref="jzDataSource"></entry>
<entry key="jl" value-ref="jlDataSource"></entry>
<entry key="bd" value-ref="bdDataSource"></entry>
</map>
</property>
<property name="defaultTargetDataSource" ref="dataSource1"></property>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dynamicDatasource" />
用到两个类
DynamicDataSourceHolder
public class DynamicDataSourceHolder
{
private static final ThreadLocal<String> holder = new ThreadLocal<String>();
public static void putDataSourceName(String name)
{
holder.set(name);
}
public static String getDataSourceName()
{
return holder.get();
}
public static void clearDataSource()
{
holder.remove();
}
}
DynamicDataSource
public class DynamicDataSource extends AbstractRoutingDataSource
{
protected Logger logger = LoggerFactory.getLogger(getClass());
@Override
public void setTargetDataSources(Map targetDataSources)
{
super.setTargetDataSources(targetDataSources);
}
@Override
public Object unwrap(Class iface) throws SQLException
{
return null;
}
@Override
public boolean isWrapperFor(Class iface) throws SQLException
{
return false;
}
@Override
public Object determineCurrentLookupKey()
{
String dataSourceName = DynamicDataSourceHolder.getDataSourceName();
logger.info("当前数据源 :" + dataSourceName);
return dataSourceName;
}
}
action中调用
@Override
public String list() throws Exception
{
lotname = lottypeService.getLotTypeById(lotid).getLt_name();
//SpObserver.putSp(LotterySetting.getLotShortName(lotid));
DynamicDataSourceHolder.putDataSourceName(LotterySetting.getLotShortName(lotid));
super.getPage().setTotalCount(gExpectService.getRecordCount(lotid));
expectList = gExpectService.getExpects(lotid, super.getPage());
return LIST;
}