在我们的代码中,我们通常使用以下模式:
Connection conn;
try{
conn = getConnection();
//Do databasey stuff
}catch(Exceptions that get thrown){
}finally{
try{
conn.close();
}catch(SQLException ex){
logger.error("Failed to cleanup database connection",ex);
}
}
然而 findbugs 不喜欢这样。由于 conn.close() 可能会引发异常,因此不能保证连接被关闭。
findbugs 是否太迂腐了,或者是否有更好的方法来关闭数据库连接。
编辑:
在 close 附近添加了已删除的 try catch。
你真正想做的是将“精英绅士”的答案与@edu.umd.cs.findbugs.annotations.SuppressWarnings( "OBL_UNSATISFIED_OBLIGATION" )
注解。 FindBugs 似乎只有在您按照以下方式完全关闭方法时才会感到高兴(顺便说一句,这是这样做的首选顺序):
...
}finally{
try{
resultSet.close();
}catch( SqlException e ){
//log error
}finally{
try{
statement.close();
}catch( SqlException e ){
//log error
}finally{
try{
connection.close();
}catch( SqlException e ){
//log error
}
}
}
}
这是非常冗长的,如果只是出于对腕管的热爱,您可能不想这样做,因此您应该使用DBUtils.closeQuietly()
方法(或创建您自己的、您的调用)。但是,FindBugs 不会将此(即使用库或您自己的方法)识别为正确关闭资源并向您发出警告。在这种情况下,它显然是一个假阳性 http://en.wikipedia.org/wiki/False_positive#Type_I_error。因此,必须确保它是您收到的唯一警告,然后禁用该方法的特定警告。
@edu.umd.cs.findbugs.annotations.SuppressWarnings( "OBL_UNSATISFIED_OBLIGATION" )
public void doStuff( final Connection connection ){
try{
//Do databasey stuff
}catch( SqlException e ){
//throw a glorious exception....
}finally{
DbUtils.closeQuietly( resultSet );
DbUtils.closeQuietly( statement );
DbUtils.closeQuietly( connection );
}
通过这种方式,您可以使用几行代码清理资源并避免 FindBugs 警告。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)