我有一个包含许多方法的 DAO 类,这些方法有很多重复的代码:-
public void method1(...) {
Connection conn = null;
try {
//custom code here
} catch (SQLException e) {
LOG.error("Error accessing the database.", e);
throw new DatabaseException();
} catch (QueryNotFoundException e) {
LOG.error("Error accessing the database.", e);
throw new DatabaseException();
} finally {
if (conn != null)
connectionPool.returnConnection(conn);
}
public void method2(...) {
Connection conn = null;
try {
//different custom code here
} catch (SQLException e) {
LOG.error("Error accessing the database.", e);
throw new DatabaseException();
} catch (QueryNotFoundException e) {
LOG.error("Error accessing the database.", e);
throw new DatabaseException();
} finally {
if (conn != null)
connectionPool.returnConnection(conn);
}
我想重组这个类,将 try、catch、finally 放在一个地方以避免重复。我将如何做到这一点?
最佳答案
为ex创建一个接口(interface)。可执行文件:
public interface Executable() {
void exec() throws SqlException();
}
将您的每个 dao 方法重构为:
public void method1() {
execute(new Executable() {
@Override
public void exec() throws SqlException() {
// your code here
}
});
}
在您的 DAO 中创建以下方法执行:
private void execute(Executor ex) {
try {
ex.exec();
} catch(...) {
...
} finally {
...
}
}
关于Java 从 DAO 中删除重复的 try、catch、finally 样板文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4459974/