spring中使用了回調函數

spring中使用了回調函數:我看到許多人對於這個回調函數的使用不知如何去理解,通過看源碼,這裏我談下自己的觀點

 

1.spring中的回調函數例子:

如:

((Integer)getHibernateTemplate().execute(new HibernateCallback() {
        public Object doInHibernate(Session session) throws HibernateException {
         int i=0;
         Statement st = null;
        
         System.out.println("session==================="+session);
         try{
            Connection con = session.connection();
            st = con.createStatement();
log.debug("exec sql:"+sql);           
            i=st.executeUpdate(sql);
          }catch (SQLException ex) {
           //System.out.println("inin================="+ex.getMessage());
           throw new DataAccessResourceFailureException(ex.getMessage());
         

          }finally{
           try {
      st.close();
     } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
          }
          return new Integer(i);
        }
      })).intValue();
  

 

然後------------

public Object execute(HibernateCallback action, boolean exposeNativeSession) throws DataAccessException {
  Assert.notNull(action, "Callback object must not be null");

  Session session = getSession();
  boolean existingTransaction = SessionFactoryUtils.isSessionTransactional(session, getSessionFactory());
  if (existingTransaction) {
   logger.debug("Found thread-bound Session for HibernateTemplate");
  }

  FlushMode previousFlushMode = null;
  try {
   previousFlushMode = applyFlushMode(session, existingTransaction);
   enableFilters(session);
   Session sessionToExpose = (exposeNativeSession ? session : createSessionProxy(session));
   Object result = action.doInHibernate(sessionToExpose);//這裏就是回調接口中的方法
   flushIfNecessary(session, existingTransaction);
   return result;
  }
  catch (HibernateException ex) {
   throw convertHibernateAccessException(ex);
  }
  catch (SQLException ex) {
   throw convertJdbcAccessException(ex);
  }
  catch (RuntimeException ex) {
   // Callback code threw application exception...
   throw ex;
  }
  finally {
   if (existingTransaction) {
    logger.debug("Not closing pre-bound Hibernate Session after HibernateTemplate");
    disableFilters(session);
    if (previousFlushMode != null) {
     session.setFlushMode(previousFlushMode);
    }
   }
   else {
    // Never use deferred close for an explicitly new Session.
    if (isAlwaysUseNewSession()) {
     SessionFactoryUtils.closeSession(session);
    }
    else {
     SessionFactoryUtils.closeSessionOrRegisterDeferredClose(session, getSessionFactory());
    }
   }
  }
 }
-------------------------解釋下這裏的回調-----------------

就是系統調用execute()方法,這時候因爲execute()方法需要一個接口類型的參數,那麼如何給他一個這樣的參數呢,方式好幾種,這裏採用的是匿名內部類的實現方式,最後execute得到了需要的參數後,再調用傳給它的接口的方法。

 

如果還不明白舉個生動的例子:

 

我有個問題需要問你,這時候我打電話給你,這個就相當主調函數,但是你需要思考一下答案才能回答我,我就只有把號碼給你了,第二天你想到了答案在打電話給我說答案,就相當於是回調了

這裏的execute就是回調函數,他需要我給他一個參數,然後它再去調用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章