问题
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:
Create your own wrapper class - either by extending Tomcat's
DataSource
class or by implementing Java'sDataSource
interface and delegating to the wrappedDataSource
- and then add the logic you want to the desired methods and register a bean in a@Configuration
class by manually instantiating yourtomcat-jdbc
DataSource
(for examples on how to do so, refer to DataSourceConfiguration.Tomcat class) and wrapping it with your class.Create an aspect and use Spring's AOP support to intercept calls to
getConnection
. SinceDataSource
class 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