当你用到多个数据源的时候,总不能创建多个sessionFactory
扩展Spring的AbstractRoutingDataSource抽象类(该类充当了DataSource的路由中介, 能有在运行时, 根据某种key值来动态切换到真正的DataSource上。
获取数据源
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
return DataSourceHolder.getDataSources();
}
}
设置数据源
public class DataSourceHolder {
private static final ThreadLocal<String> dataSources = new ThreadLocal<String>();
public static void setDataSources(String dataSource) {
dataSources.set(dataSource);
}
数据源切换
public class DataSourceExchange {
/**
*
* @param point
*/
public void before(JoinPoint point) {
//获取目标对象的类类型
Class<?> aClass = point.getTarget().getClass();
//获取包名用于区分不同数据源
String whichDataSource = aClass.getName();
if (!"com.wanhejia.service.impl.UserServiceImpl".equals(whichDataSource)) {
DataSourceHolder.setDataSources("dataSource1");
} else {
DataSourceHolder.setDataSources("dataSource2");
}
}
/**
* 执行后将数据源置为空
*/
public void after() {
DataSourceHolder.setDataSources(null);
}
public static String getDataSources() {
return dataSources.get();
}
}
配置文件书写
<bean id="dataSourceExchange" class="com.wanhejia.utils.DataSourceExchange"/>
<aop:config proxy-target-class="false">
<!--所有数据库操作的方法加入切面-->
<aop:aspect ref="dataSourceExchange">
<aop:pointcut id="dataSourcePointcut" expression="e x e cution(* com.wanhejia.service.*.findByNames(..))"/>
<aop:before pointcut-ref="dataSourcePointcut" method="before"/>
<aop:after pointcut-ref="dataSourcePointcut" method="after"/>
</aop:aspect>
</aop:config>
<bean id="dataSource" class="com.wanhejia.utils.DynamicDataSource">
<property name="targetDataSources">
<map key-type="java.lang.String">
<entry key="dataSource1" value-ref="dataSource1"/>
<entry key="dataSource2" value-ref="dataSource2"/>
</map>
</property>
<!--默认数据源-->
<property name="defaultTargetDataSource" ref="dataSource1"/>
</bean>