声纳 squid:S2095 当方法 return 连接
Sonar squid:S2095 when method return Connection
使用方法返回 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.
我想要return一个以后可以使用的连接,所以我不能用那些方法关闭它
How/if 我可以避免在 return 有效连接的主要方法上出现这样的警告吗?
编辑
在 Sonar 社区中添加了误报错误:S2095 report on method return Connection
编辑 2 问题在最新版本上无法重现
从技术上讲,SonarQube(在本例中为 SonarJava 分析器)无法保证此方法返回的连接最终会关闭 - 因此会出现问题。
如果您确信您的代码库在其他地方有所有必需的资源清理代码,我的建议是在 SonarQube UI 中将此特定问题标记为 Won't fix
。
我在创建与 mongodb 的连接时遇到了类似的问题。所以,我刚刚创建了连接对象 Autowired
,因为我正在使用 spring.
这样,连接对象的生命周期由spring管理,我们不必显式关闭连接。
使用方法返回 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.
我想要return一个以后可以使用的连接,所以我不能用那些方法关闭它
How/if 我可以避免在 return 有效连接的主要方法上出现这样的警告吗?
编辑 在 Sonar 社区中添加了误报错误:S2095 report on method return Connection
编辑 2 问题在最新版本上无法重现
从技术上讲,SonarQube(在本例中为 SonarJava 分析器)无法保证此方法返回的连接最终会关闭 - 因此会出现问题。
如果您确信您的代码库在其他地方有所有必需的资源清理代码,我的建议是在 SonarQube UI 中将此特定问题标记为 Won't fix
。
我在创建与 mongodb 的连接时遇到了类似的问题。所以,我刚刚创建了连接对象 Autowired
,因为我正在使用 spring.
这样,连接对象的生命周期由spring管理,我们不必显式关闭连接。