---
title: "Spring-模板方法模式及Callback"
author: "explore"
date: "2010-05-17T12:20:26Z"
tags: []
categories: ["企业架构"]
slug: "spring-callback"
draft: false
lastmod: "2010-05-17T13:57:04Z"
id: 667992
url: "https://explore.iteye.com/blog/667992"
---

Spring对JDBC的抽象和对Hibernate的集成，都采用了一种理念或者处理方式，那就是模板方法模式与相应的Callback接口相结合。

 

 采用模板方法模式是为了以一种统一而集中的方式来处理资源的获取和释放，以JdbcTempalte为例，如下：

 

```
public abstract class JdbcTemplate {
      
      public final Object execute（String sql）{
            Connection con=null;
            Statement stmt=null;
             try
             {
                 con=getConnection（）;
                 stmt=con.createStatement（）;
                 Object retValue=executeWithStatement（stmt,sql）;
                 return retValue;
             }
             catch（SQLException e）{
                 ...
             }
             finally
             {
               closeStatement（stmt）;
               releaseConnection（con）;
             }
       }

       protected abstract Object executeWithStatement（Statement   stmt, String sql）;
}
```

   这样处理之后，JDBC代码的使用得到了规范，连接释放等问题也得到了统一的管理。

  但是，JdbcTemplate是抽象类，不能够独立使用，我们每次进行数据访问的时候都要给出一个相应的子类实现,这样肯定不方便，所以就引入了回调。

```
public interface StatementCallback{
      Object doWithStatement（Statement stmt）;
}
```

  

 

```
public class JdbcTemplate {
      
      public final Object execute（StatementCallback callback）{
            Connection con=null;
            Statement stmt=null;
             try
             {
                 con=getConnection（）;
                 stmt=con.createStatement（）;
                 Object retValue=callback.doWithStatement（stmt）;
                 return retValue;
             }
             catch（SQLException e）{
                 ...
             }
             finally
             {
               closeStatement（stmt）;
               releaseConnection（con）;
             }
       }

       ...//其它方法定义
}
```

 

使用如下：

 

```
JdbcTemplate jdbcTemplate=...;
final String sql=...;
StatementCallback callback=new StatementCallback(){
      public Object=doWithStatement(Statement stmt){
             return ...;
      }
}

jdbcTemplate.execute(callback);
```