SpringMVC 使用jndi 多个数据源且动态切换
配合上一章我们来进一步让SpingMVC使用jndi 多个数据源且能够动态切换
1. <beanid="dbe2"class="org.springframework.jndi.JndiObjectFactoryBean">
2. <propertyname="jndiName">
3. <value>java:comp/env/jndi/dbe2</value>
4. </property>
5. </bean>
6. <beanid="dbcpccj"class="org.springframework.jndi.JndiObjectFactoryBean">
7. <propertyname="jndiName">
8. <value>java:comp/env/jndi/dbcpccj</value>
9. </property>
10. </bean>
11. <beanid="dataSource"class="com.wishbuild.persistent.source.DynamicDataSource">
12. <propertyname="targetDataSources">
13. <mapkey-type="java.lang.String" value-type="com.wishbuild.persistent.source.DataSourceType">
14. <entryvalue-ref="dbe2"key="dbe2"></entry>
15. <entryvalue-ref="dbcpccj"key="dbcpccj"></entry>
16. </map>
17. </property>
18. <propertyname="defaultTargetDataSource"ref="dbe2"></property>
19. </bean>
- 配置 java 代码
public class DataSourceType {
public static final String dbe2 = "dbe2";
public static final String dbcpccj = "dbcpccj";
}
- 将接收类型定义为String
public class DataSourceLoadServer {
private static final ThreadLocal<Object> holder = new ThreadLocal<Object>();
public static void setDataSourceType(String dbType) {
holder.set(dbType);
}
public static String getDataSourceType() {
return (String) holder.get();
}
public static void clearDataSourceType() {
holder.remove();
}
}
- 利用AbstractRoutingDataSource实现动态数据源切换
public class DynamicDataSource extends AbstractRoutingDataSource {
<span style="white-space:pre"> </span>public static final Logger logger = Logger.getLogger(DynamicDataSource.class.toString());
<span style="white-space:pre"> </span>
<span style="white-space:pre"> </span>@Override
<span style="white-space:pre"> </span>protected Object determineCurrentLookupKey() {
<span style="white-space:pre"> </span>String key = DataSourceLoadServer.getDataSourceType();
<span style="white-space:pre"> </span>return key;
<span style="white-space:pre"> </span>}
}
- 动态切换代码
DataSourceLoadServer.setDataSourceType(DataSourceType.dbtest1);