1、查看源码

AbstractRoutingDataSource类中有个determineTargetDataSource方法

 protected DataSource determineTargetDataSource() {
        Assert.notNull(this.resolvedDataSources, "DataSource router not initialized");
        Object lookupKey = this.determineCurrentLookupKey();
        DataSource 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 + "]");
        } else {
            return dataSource;
        }
    }
determineTargetDataSource会调用抽象方法determineCurrentLookupKey
@Nullable
    protected abstract Object determineCurrentLookupKey();

2、创建类继承AbstractRoutingDataSource

 1 import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
 2 
 3 public class DynamicDataSource extends AbstractRoutingDataSource{
 4 
 5     @Override
 6     protected Object determineCurrentLookupKey() {
 7         return DynamicDataSourceHolder.getDbType();
 8     }
 9 
10 }
DynamicDataSource

相关文章: