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就是回调函数,他需要我给他一个参数,然后它再去调用