在我的Spring應用程序中,我需要根據應用程序配置中設置的某些值動態初始化多個數據源。 我知道Spring jdbc庫提供的AbstractRoutingDataSource類,但它只有在需要基於一次查找鍵值初始化單個數據源時纔有用。在Spring中動態初始化多個數據源
是否可以擴展AbstractRoutingDataSource並更改其行爲以支持多鍵查找和數據源解析?還有其他的方法嗎? Reference
基本上我想通過AbstractDataSourceRouter類來實現這樣的事情:
public class DataSourceRouter extends AbstractRoutingDataSource {
@Value("${com.listdb.datasource.switch}")
private short listDBSwitch;
@Value("${com.scoringdb.datasource.switch}")
private short scoringDbSwitch;
@Value("${com.configmaster.datasource.switch}")
private short configDbSwitch;
private List<String> configuredDataSources;
/**
* Determine the current lookup key. This will typically be
* implemented to check a thread-bound transaction context.
* <p>Allows for arbitrary keys. The returned key needs
* to match the stored lookup key type, as resolved by the
* {@link #resolveSpecifiedLookupKey} method.
*/
@Override
protected Object determineCurrentLookupKey() {
if(ListUtil.isListNotEmpty(configuredDataSources)) {
configuredDataSources =new ArrayList<String>();
String listDBString = (listDBSwitch == 1)?DataSources.LIST.toString() : null;
String configDBString = (configDbSwitch == 1) ? DataSources.CONFIGMASTER.toString() :null;
String scoringDBString = (scoringDbSwitch == 1) ? DataSources.SCORING.toString() : null;
/**
* Add all configured data source keys for look up
*/
configuredDataSources.add(listDBString);
configuredDataSources.add(configDBString);
configuredDataSources.add(scoringDBString);
}
return configuredDataSources;
}
}
任何幫助/建議?