Razvan Popian opened SPR-16509 and commented

org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource#determineTargetDataSource will throw an exception if it can not return a DataSource for the current lookup key. This class could be modified or extended so that if there is no DataSource for the current key, one could be loaded/created. This would be useful in scenarios where new data sources are created while the program using the routing data source is running. The program would not need to be restarted if the routing data source would lazily pick up newly created data sources. I needed this feature on a project so I created a subclass of the AbstractRoutingDataSource, I attached it to the ticket, in case it is useful to somebody. The implementation is a bit messy because it uses reflection to access certain private things in the super class.


Affects: 4.3.10

Attachments: - AbstractNewDsAwareRoutingDataSource.java (9.11 kB) - LazyAbstractRoutingDataSource.java (2.08 kB)

1 votes, 3 watchers

Comment From: spring-projects-issues

Razvan Popian commented

I would be interested in working on this issue, I have read the guide https://github.com/spring-projects/spring-framework/blob/master/CONTRIBUTING.md, but it is not clear to me if I could submit a pull request for an issue that is waiting for triage. Thanks.

Comment From: spring-projects-issues

Matías Paciulli commented

We are having this same need. In the company we have servers and we want to instantiate the DataSource on demand, when the users make their first entry into the Database. We have a schema with multiple databases, and we want to create a configuration to determine a data source type, by server or by tenant. Extending from AbstractRoutingDataSource we made another class that overwrites the "determineTargetDataSource" method and adds a new one "getDataSource ()". We also had the need to change the modifiers of the attributes of the "AbstractRoutingDataSource" class, from private to protected. These attributes are: resolvedDataSources and resolvedDefaultDataSource. We think it would be good if the class we call LazyAbstractRoutingDataSource is added to the spring package of the next version, or that you share your opinions on the best way in this case. Attached below is the .java file with the proposed solution.

Comment From: snicoll

AbstractRoutingDataSource is really meant to work against a preset of existing datasources. Allowing datasources to be created on-the-fly has obvious concurrency problem that the current implementation doesn't handle at this time. We'd be open to open the contract a bit to offer more flexibility, but without dealing the concurrency bit I doubt it would be much useful.