先看类:
//该类继承自AbstractDataSource,说明本身就是个DataSource可以这么理解,还实现了InitializingBean
//说明在bean初始化过程中执行了afterPropertiesSet方法
public abstract class AbstractRoutingDataSource extends AbstractDataSource implements InitializingBean {
@Nullable
private Map<Object, Object> targetDataSources;//存放所有的数据源
@Nullable
private Object defaultTargetDataSource;//默认数据源
private boolean lenientFallback = true;
private DataSourceLookup dataSourceLookup = new JndiDataSourceLookup();
//这两个属性在afterPropertiesSet方法中被赋值了,也是存放数据源的
@Nullable
private Map<Object, DataSource> resolvedDataSources;
@Nullable
private DataSource resolvedDefaultDataSource;
}
我们从上面可以看到本身这个类就是一个DataSource,那必然有getConnection(),还记得我们使用原生的数据源连接时是怎么写的
DataSource.getConnection();
//执行查询等
connection.close();
@Override
public Connection getConnection() throws SQLException {
return determineTargetDataSource().getConnection();
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
return determineTargetDataSource().getConnection(username, password);
}
调用了determineTargetDataSource这个方法
protected DataSource determineTargetDataSource() {
//为null断言
Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
//获取lookupKey,后面都是根据这个获取数据源的
Object lookupKey = determineCurrentLookupKey();
//从map中拿
DataSource dataSource = this.resolvedDataSources.get(lookupKey);
if (dataSource == null && (this.lenientFallback || lookupKey == null)) {
dataSource = this.resolvedDefaultDataSource;
}
if (dataSource == null) {
throw new IllegalStateException("Cannot determine target DataSource for lookup key [" + lookupKey + "]");
}
return dataSource;
}
所以我们只需要自定义类继承AbstractRoutingDataSource并重写determineTargetDataSource方法即可
当然前提是我们还要想办法把这个类作为bean管理并且填充其属性值:
@Nullable private Map<Object, Object> targetDataSources; @Nullable private Object defaultTargetDataSource;
思路应该是:想办法把配置文件中配置所有的数据源都配置为bean,并且把AbstractRoutingDataSource配置为bean并且填充属性即可
实现:https://blog.csdn.net/dong__xue/article/details/115558591