简体   繁体   English

如何关闭通过Spring创建的jdbc连接?

[英]How to close a jdbc connection created through Spring?

I've built an application (app1) that looks at and records certain fields in a database. 我已经构建了一个应用程序(app1),用于查看并在数据库中记录某些字段。 This application shares the database with another application (app2) that requires a solitary connection to it when starting up but is fine to allow other connections to the DB once it (app2) is started. 此应用程序与另一个在启动时需要单独连接的应用程序(app2)共享数据库,但可以很好地允许数据库(app2)启动后与数据库建立其他连接。 In my application (app1), I have made a dao object using Spring to connect to the DB and evidently, the connection is never closed which causes app2 to crash upon start up. 在我的应用程序(app1)中,我使用Spring制作了一个dao对象以连接到数据库,显然,连接从未关闭,这导致app2在启动时崩溃。 From what I've read, Spring is supposed to automatically handle opening and closing all of the DB connections it manages. 根据我的阅读,Spring应该能够自动处理打开和关闭它管理的所有数据库连接。 I'm not sure of any code I could share to help paint a better picture of my problem but if some is needed, I'll post what I can. 我不确定我可以共享任何代码来帮助更好地描绘我的问题,但是如果需要一些代码,我会尽力而为。 Thanks for any help. 谢谢你的帮助。

如果您使用的是JDBC模板,则不必担心显式关闭连接,Spring将负责内部管理连接池以及从该池获取/释放连接。

When sharing connections between applications I would recommend using a connection pool. 在应用程序之间共享连接时,我建议使用连接池。 Opening and closing of connections could be done by declarative transaction demarcation via annotations (@Transactional). 连接的打开和关闭可以通过注释(@Transactional)通过声明式事务划分来完成。

http://faheemsohail.com/2012/01/configuring-c3p0-connection-pooling-with-spring-and-hibernate/ http://faheemsohail.com/2012/01/configuring-c3p0-connection-pooling-with-spring-and-hibernate/

Would this work for you? 这对您有用吗?

 public  void closeCon() {

  {
   if (con != null)
    try {
     con.close();

    } catch (SQLException e) {
     e.printStackTrace();
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM