spring/tomcat-jdbc池-新的连接侦听器 [英] spring/tomcat-jdbc pool - new connection listener

查看:209
本文介绍了spring/tomcat-jdbc池-新的连接侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在默认的spring-boot设置中使用tomcat-jdbc池.我想每次在池中建立新的JDBC连接时以及在首次使用它之前都运行一些自定义Java代码.如何做到?如果有几种可能性,哪一种是最好的?

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?

推荐答案

好吧,我可以想到两个选择:

Well, I can think of two options:

  1. 创建您自己的包装器类-通过扩展Tomcat的DataSource类或通过实现Java的DataSource接口并委托给包装的DataSource-然后将所需的逻辑添加到所需的方法并注册通过手动实例化tomcat-jdbc DataSource@Configuration类中创建一个bean(有关如何执行此操作的示例,请参考

  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.

创建一个方面,并使用Spring的AOP支持来拦截对getConnection的调用.由于DataSource class在javax软件包中,因此我认为您必须使用AspectJ,有关某些示例,请参考

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

我的建议是选择第一个选项,这样可以减少麻烦,这是一个如何定义包装bean的小例子:

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
}

这篇关于spring/tomcat-jdbc池-新的连接侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆