Java 从 DAO 中删除重复的 try、catch、finally 样板文件

标签 java try-catch dao boilerplate

我有一个包含许多方法的 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/

相关文章:

java - Eclipse 不再检测丢失的 try/catch 吗?

java - 在 java 中的 try-catch block 之后使用 "finally"有什么好处?

java - ORMLite 外国集合 : Must use ClosableIterator?

java - 实现 MVC 时,应用程序的哪一部分应该调用 DAO 中的方法?

java - Android 模拟器错误,控制台错误日志重复错误

java - codingbat maxMirror 练习的问题

java - plsql - 如何将关联数组返回到java

Java 编码区Circle

f# - 在 F# 中缩小 try-with block ?

hibernate - Spring集成测试不回滚