</mvc:message-converters>
</mvc:annotation-driven>
《一线大厂Java面试题解析+后端开发学习笔记+最新架构讲解视频+实战项目源码讲义》
【docs.qq.com/doc/DSmxTbFJ1cmN1R2dB】 完整内容开源分享
application/json;charset=UTF-8
classpath*:jdbc.properties
<bean id=“firstSource” class=“org.apache.commons.dbcp.BasicDataSource”
destroy-method=“close”>
<bean id=“secondSource” class=“org.apache.commons.dbcp.BasicDataSource”
destroy-method=“close”>
mvc:interceptors
</mvc:interceptors>
然后是定义动态数据源,DynamicDataSource.java:
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
/**
-
@Author : JCccc
-
@CreateTime : 2019/8/15
-
@Description :
**/
public class DynamicDataSource extends AbstractRoutingDataSource{
//定义动态数据源,集成spring提供的AbstractRoutingDataSource,实现determineCurrentLookupKey
@Override
protected Object determineCurrentLookupKey() {
return DynamicDataSourceHolder.getDataSource();
}
}
接着是动态切换数据源方法类,DynamicDataSourceHolder.java:
/**
-
@Author : JCccc
-
@CreateTime : 2019/8/15
-
@Description :
**/
public class DynamicDataSourceHolder
{
private static final ThreadLocal THREAD_DATA_SOURCE = new ThreadLocal();
public static String getDataSource()
{
return (String)THREAD_DATA_SOURCE.get();
}
public static void setDataSource(String dataSource)
{
THREAD_DATA_SOURCE.set(dataSource);
}
public static void clearDataSource()
{
THREAD_DATA_SOURCE.remove();
}
}
到这,多数据源已经实现了,我们在切换数据源,使用的时候只需要用以下这行代码进行切换:
DynamicDataSourceHolder.setDataSource(“XXXX”); //值为配置文件里面数据源设置的加载key
最后测试下,写一个接口简单测试下:
@Autowired
MessageboardService messageboardServiceImpl;
@Autowired
JdbcConfigService jdbcConfigServiceImpl;
@RequestMapping(value = “/testDbSource”, produces = “application/json; charset=utf-8”)