Java从DAO中删除重复的try,catch,最后的样板

Tar*_*ski 4 java dao try-catch 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);
  } 
Run Code Online (Sandbox Code Playgroud)

我想重组这个课程,把try,catch,最后放在一个地方,以避免重复.我怎么做到这一点?

Vla*_*nov 7

为ex创建一个接口.可执行文件:

 public interface Executable() {

   void exec() throws SqlException();

 }
Run Code Online (Sandbox Code Playgroud)

将每个dao方法重构为:

public void method1() {
   execute(new Executable() {

     @Override
     public void exec() throws SqlException() {
          // your code here
     }
  });
  } 
Run Code Online (Sandbox Code Playgroud)

在DAO中创建以下方法:

private void execute(Executor ex) {
    try {
      ex.exec();
    } catch(...) {
      ...
    } finally {
       ...
    }
}
Run Code Online (Sandbox Code Playgroud)