2010-12-16 8 views
4

から最終的には定型を削除します -Javaの私はの線に沿って繰り返されるコードの多くを持っている多くの方法でDAOクラスを持って繰り返し試して、キャッチ、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を一箇所に入れてください。どうすればこれを達成できますか?

答えて

6

がexのためのインタフェースを作成します。実行可能ファイル:へ

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 { 
     ... 
    } 
} 
+0

Yup、それはJdbcTemplateがオプションではない場合に提案する次のパターンです+1) –

1

ここでは、commongロギングパターンにAOPを使用します。例えば: -

<bean id="exceptionLogger" class="my.good.ExceptionLogger" /> 
    <aop:config> 
      <aop:pointcut id="allDaoMethods" expression="execution(* my.dao.*(..))" /> 
      <aop:aspect id="daoLogger" ref="exceptionLogger"> 
       <aop:after-throwing pointcut-ref="allDaoMethods" 
            method="logIt" 
            throwing="e"/> 
      </aop:aspect> 
    </aop:config> 

そしてExceptionLoggerクラスは以下のようなものが考えられます。 -

public class ExceptionLogger { 
    private static Logger logger = Logger.getLogger(ExceptionLogger.class); 
    public void logIt(JoinPoint jp, Exception e) { 
     StringBuilder msg = new StringBuilder(); 
     msg.append("<whatever makes sense>"); 
     logger.error(msg.toString()); 
    } 
} 
+0

私にとっては面白いです。もっと説明できますか?私は同じ状況にあります –

+0

あなたは私に何かもっと説明したいですか?私が提供したリンクでAOPについて読むことができます。私はaop configとサンプル例外クラスの例も示しました。 – CoolBeans

+0

これはまた、春に基づいたソリューションです。この章を読んでください:http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/aop.html(読みにくいですが、努力する価値があります)、 'AspectJ in Action(2nd ed) ':http://www.manning.com/laddad2/ Springの有無にかかわらず、AOPの詳細なカバーを提供しています。 –

2

私は何を使うべきことSpring-JDBC年代だと思いますJdbcTemplate

spring to maを使用しない場合でもJdbcTemplateをプログラムで使用して、すべての接続管理とエラー処理を抽象化することができます。

コード例:あなたが見ることができるように

List<Actor> actors = this.jdbcTemplate.query(
     "select first_name, last_name from t_actor", 
     new RowMapper<Actor>() { 
      public Actor mapRow(ResultSet rs, int rowNum) 
      throws SQLException { 
       Actor actor = new Actor(); 
       actor.setFirstName(rs.getString("first_name")); 
       actor.setLastName(rs.getString("last_name")); 
       return actor; 
      } 
     }); 

は、あなただけではなく、その周りのインフラストラクチャのものと実際のクエリを扱います。

0

これは、そのようなメソッドから値を返す可能性のある匿名クラスを持たないVladimirsソリューションに似ています。

interface DaoOperation { 
    void execute() throws SQLException; 
} 

class Operation1 implements DaoOperation { 

    public void execute() { 
     // former method1 
    } 
} 

// in case you'd ever like to return value 
interface TypedDaoOperation<T> { 
    T execute() throws SQLException; 
} 

class Operation2 implements TypedDaoOperation<String> { 
    public String execute() { 
     return "something"; 
    } 
} 

class DaoOperationExecutor { 
    public void execute(DaoOperation o) { 
     try { 
      o.execute(); 
     } catch (SQLException e) { 
      // handle it as you want 
     } 
    } 

    public <T>T execute(TypedDaoOperation<T> o) { 
     try { 
      return o.execute(); 
     } catch (SQLException e) { 
      // handle it as you want 
     } 
    } 
} 
関連する問題