2

为什么使用 AbstractRoutingDataSource 不能动态切换 DataSource 这是配置信息

public class DynamicSwitch {
    public static final ThreadLocal<String> local=new ThreadLocal<String>();

    public static void setDB(String id){
        local.set(id);
    }
    public static String getDB(){
        return local.get();
    }
    public static void removeDB(){
         local.remove();
    }
}

public class DynamicSource extends AbstractRoutingDataSource implements InitializingBean{
    @Override
    protected Object determineCurrentLookupKey() {
        // TODO Auto-generated method stub
        return DynamicSwitch.getDB();
    }
}

<bean id="dynamic" class="com.aware.DynamicSource">
    <property name="targetDataSources">
        <map key-type="java.lang.String">
                <entry key="1" value-ref="dataSource"></entry>
                <entry key="2" value-ref="localdataSource"></entry>
        </map>
    </property>
    <property name="defaultTargetDataSource" ref="dataSource"></property>
</bean>

<bean id="methodService" class="com.test.service.MethodServiceImpl">
    <property name="sqlMapClient" ref="sqlMapClient"></property>
</bean>

<bean id="test" class="com.test.Test" scope="prototype"></bean>

public class Test2 extends ActionSupport{

    public String execute() throws Exception {
        // TODO Auto-generated method stub
        DynamicSwitch.setDB("2");
        MethodService methodService=(MethodService)ApplicationAware.getBean("methodService");
        Map<String, String> map=new HashMap<String, String>();
        List list=methodService.testList("Service_ks_missionSpace.getService_ks_missionList", map);
        System.out.println(list.size());
        return SUCCESS;
}

调用 DynamicSwitch.setDB("2") 发现不能切换数据源。DataSource 还是默认dataSource 为什么

4

0 回答 0