我們目前有一個應用程序使用具有相同模式的多個數據庫。目前我們正在使用自定義解決方案來根據用戶的會話在它們之間進行切換。此作品通過無法創建需要來自另一個數據庫某些數據的AbstractRoutingDataSource
public final class DataSourceProxy extends BasicDataSource {
...
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null && auth.getDetails() instanceof Map) {
Map<String, String> details = (Map<String, String>) auth.getDetails();
String targetUrl = details.get("database");
Connection c = super.getConnection();
Statement s = c.createStatement();
s.execute("USE " + targetUrl + ";");
s.close();
return c;
} else {
return super.getConnection();
}
}
現在我們要使用AbstractRoutingDataSource
構建解決方案。問題是:
@Component
public class CustomRoutingDataSource extends AbstractRoutingDataSource {
@Autowired
Environment env;
@Autowired
DbDetailsRepositoy repo;
public CustomRoutingDataSource() {
Map<Object, Object> targetDataSources = new HashMap<Object, Object>();
for(DBDetails dbd : repo.findAll() {
// create DataSource and put it into the map
}
setTargetDataSources(new HashMap<Object, Object>());
}
@Override
protected Object determineCurrentLookupKey() {
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
if (auth != null && auth.getDetails() instanceof Map) {
Map<String, String> details = (Map<String, String>) auth.getDetails();
return details.get("database");
}
return null;
}
}
在構造函數中(或者甚至通過@PostConstruct
)我們必須填補targetDataSources Map
。但是(!)爲此我們需要存儲在另一個數據庫中的連接細節,這個數據庫有自己的數據源和實體管理器。
看來Spring似乎無法確定Bean構造的順序,或者我只是錯過了一些東西。訪問存儲庫時,它總是給出NullPointerException
(其中btw是JpaRepository
)。
我們使用Spring 3.2.3,Spring Data,Hibernate 4.2。 Spring和Spring Security的完整註釋和Java-Code配置。
請幫助我們!
對沒錯...有時候人們無法看到的最明顯的事情 –