Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SimpleJDBCTemplate and AbstractDataSource configuration

I am working on an app that uses SimpleJDBCTemplate as the wrapper to make JDBC calls.

However, instead of a conventional Datasource, I am choosing to use AbstractDataSource so I can choose from multiple data sources.

I am using ThreadLocal to inject keys to choose the appropriate Datasource.

However, it appears Spring is eagerly creating all my DAOs and my jdbcTemplate and hence I cannot figure out how to have the jdbcTemplate get Connection on demand.

Any clues.?

like image 692
Anand Hemmige Avatar asked Dec 28 '25 14:12

Anand Hemmige


1 Answers

Do you mean AbstractRoutingDataSource? If not, you really should be using that, since this is exactly what it's for. Mark Fisher wrote a useful blog about it back when it was added to the framework.

Yes Spring will create your DAOs and JdbcTemplates eagerly if they're singletons, which is the default, but that doesn't mean they all obtain a connection immediately. A connection will only be obtained when you start some kind of operation that uses that data source. Typically, that would be starting a transaction. In other words, what you say you want to happen is what already happens.

like image 118
Ryan Stewart Avatar answered Jan 01 '26 23:01

Ryan Stewart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!