//实际方法
//现在是一个嵌套try,并且还是未进行优化的关流
public void saveMessage(String keycde,String xmlStr,String type,String fromStr) throws PublicException{
Connection conn = null;
PreparedStatement state = null;
try {
try {
conn = this.commonDao.getNewConnection();
} catch (Exception e) {
logger.error(e.getMessage(), e);
throw new PublicException(“保存报文失败:获取不到连接”,e);
}
String sql = “insert into web_interface_msg” +
“(C_ID,C_KEY_CDE,C_MSG,C_REQUEST_TYPE,C_FROM,C_CRT_CDE,T_CRT_TM,C_UPD_CDE,T_UPD_TM)”
+ " values"
+ “(replace(uuid(), ‘-’, ‘’),?,?,?,?,?,now(),?,now())”;
state = conn.prepareStatement(sql);
state.setString(1, keycde);
state.setCharacterStream(2, new StringReader(xmlStr), xmlStr.length());
state.setString(3, type);
state.setString(4, fromStr);
state.setString(5, “posService”);
state.setString(6, “posService”);
state.execute();
} catch (SQLException e) {
logger.error(e.getMessage(), e);
throw new PublicException(“保存报文失败”,e,“1”);
} finally {
try {
if (state != null) {
state.close();
state = null;
}
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
logger.error(e.getMessage(), e);
}
}
}
//实际就是把之前需要在finally关闭的资源流,放在try后的()中,这个语法糖会在try代码块执行完后自动调用try()中对象的close()方法。即可实现资源快速关闭
//这个方法是AutoCloseable的方法,他在jdk7中作为closeable的基类出现
public void saveMessage(String keycde,String xmlStr,String type,String fromStr) throws PublicException{
String sql = “insert into web_interface_msg” +
“(C_ID,C_KEY_CDE,C_MSG,C_REQUEST_TYPE,C_FROM,C_CRT_CDE,T_CRT_TM,C_UPD_CDE,T_UPD_TM)”
+ " values"
+ “(replace(uuid(), ‘-’, ‘’),?,?,?,?,?,now(),?,now())”;
try(Connection conn = this.commonDao.getNewConnection();
PreparedStatement state = conn.prepareStatement(sql)😉{
state.setString(1, keycde);
state.setCharacterStream(2, new StringReader(xmlStr), xmlStr.length());
state.setString(3, type);
state.setString(4, fromStr);
state.setString(5, “posService”);
state.setString(6, “posService”);
state.execute();
} catch (SQLException e) {
logger.error(e.getMessage(), e);
throw new PublicException(“保存报文失败”,e,“1”);
}
}
本文展示了如何使用Java的try-with-resources语法糖优化资源关闭操作,避免手动在finally块中关闭连接和预编译语句,提高代码的可读性和安全性。示例代码比较了优化前后的saveMessage方法,强调了try语句块后括号内声明的AutoCloseable资源会在执行完毕后自动调用close方法。
492

被折叠的 条评论
为什么被折叠?



