gpt4 book ai didi

java - Sonar 鱿鱼 :S2095 when method return Connection

转载 作者:行者123 更新时间:2023-11-30 12:07:56 28 4
gpt4 key购买 nike

使用方法返回 Connection 是一种常见的做法,例如在 Hikari 的 HikariConnectionProvider

public Connection getConnection() throws SQLException
   {
Connection conn = null;
if (this.hds != null) {
conn = this.hds.getConnection();
}
return conn;
}

但是Sonar警告关闭连接

Connections, streams, files, and other classes that implement the Closeable interface or its super-interface, AutoCloseable, needs to be closed after use. Further, that close call must be made in a finally block otherwise an exception could keep the call from being made.

我想返回一个以后可以使用的连接,所以我不能在那些方法中关闭它

如何/如果我可以避免在 main 方法上出现此类警告以返回有效连接?

编辑在 Sonar 社区中添加了误报错误:S2095 report on method return Connection

EDIT 2 问题在最新版本上无法重现

最佳答案

我在创建与 mongodb 的连接时遇到了类似的问题。所以,当我使用 spring 时,我刚刚创建了连接对象 Autowired

这样连接对象的生命周期由spring管理,我们不必显式关闭连接。

关于java - Sonar 鱿鱼 :S2095 when method return Connection,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54568665/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com