springjdbcspring-bootconnection-poolingtomcat-jdbc

spring/tomcat-jdbc pool - new connection listener


I am using tomcat-jdbc pool in default spring-boot setup. I would like to run some custom Java code each time new JDBC connection is established in the pool and before it is used for the first time. How to do it, and if there are several possibilities which one is the best?


Solution

  • Well, I can think of two options:

    1. Create your own wrapper class - either by extending Tomcat's DataSource class or by implementing Java's DataSource interface and delegating to the wrapped DataSource - and then add the logic you want to the desired methods and register a bean in a @Configuration class by manually instantiating your tomcat-jdbc DataSource (for examples on how to do so, refer to DataSourceConfiguration.Tomcat class) and wrapping it with your class.

    2. Create an aspect and use Spring's AOP support to intercept calls to getConnection. Since DataSourceclass is in the javax package, I think you'll have to use AspectJ, and for some examples refer to this link

    My suggestion would be to go with the first option, it should give you fewer headaches, here's a small example how you'd define your wrapper bean:

    @Bean
    public DataSource dataSource(DataSourceProperties properties) {
        return new MyDataSourceWrapper(tomcatDataSourceFrom(properties));
    }
    
    private org.apache.tomcat.jdbc.pool.DataSource tomcatDataSourceFrom(
        DataSourceProperties properties) {
        // manual instantiation like in DataSourceConfiguration.Tomcat class
    }