Java 从 DAO 中删除重复的 try、catch、finally 样板
我有一个 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 放在一个地方以避免重复。我将如何实现这个目标?
I have a DAO class with many methods that have a lot of repeated code along the lines of: -
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);
}
I would like to restructure this class to put the try, catch, finally in one place to avoid repetation. How would I accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
为 ex 创建一个接口。可执行文件:
将每个 dao 方法重构为:
在 DAO 中创建以下执行方法:
Create an interface for ex. Executable:
Refactor each of your dao method to :
Create the following method execute in your DAO:
我认为你应该使用的是 Spring- JDBC 的
JdbcTemplate
即使您不使用 spring 来管理您的应用程序,您也可以以编程方式使用 JdbcTemplate 来抽象所有连接管理和错误处理。
示例代码:
如您所见,您仅处理实际查询,而不处理其周围的基础设施。
I think what you should use is Spring-JDBC's
JdbcTemplate
Even if you don't use spring to manage your application, you could programmatically use JdbcTemplate to abstract away all the connection management and error handling.
Example code:
As you can see, you deal with the actual query only, not with the infrastructure stuff around it.
我会使用 AOP 用于此处的通用日志记录模式。例如:-
ExceptionLogger 类可能如下所示:-
I would use AOP for a commong logging pattern here. For example:-
And the ExceptionLogger class could be something like below:-
这类似于没有匿名类的弗拉基米尔解决方案,可以从此类方法返回值。
This is similiar to Vladimirs solution without anonymous classes with possibility to return value from such methods.