2016-04-28 26 views
1

在我的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; 
} 

}

任何幫助/建議?

回答

0

這對於當前的spring/hibernate版本來說並不是真的可行,即使這樣做會很整潔。如果您需要多個數據源並使用AbstractRoutingDataSource來實現此目標,那麼一種可能的解決方案是讓Spring初始化一個DB(默認/配置DB)並添加例如init.sql腳本(或flyway/liquibase,如果你更喜歡這樣的話)可以在同一個AbstractRoutingDataSource下初始化所有其他的腳本。

此方法很好地工作,並讓您更好地控制(希望測試!)環境。就我個人而言,我喜歡對數據庫模式有更多的控制,然後任何自動初始化器都可以提供,但這只是一個味道/風格問題。