spring/tomcat-jdbc pool - new connection listener

◇◆丶佛笑我妖孽 提交于 2019-12-21 05:34:12

问题


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?


回答1:


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
}



回答2:


To extend already accepted answer, you can use Spring AOP without full AspectJ if you use pointcut as this one:

@AfterReturning(pointcut = "execution(* org.apache.tomcat.jdbc.pool.DataSourceProxy.getConnection())")
public void afterConnectionEstablished() {
    ...
}


来源:https://stackoverflow.com/questions/38526129/spring-tomcat-jdbc-pool-new-connection-listener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!