首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件开发 >

Spring 使用的设计形式(一) CallBack(回调)

2013-11-06 
Spring 使用的设计模式(一) CallBack(回调)public T T execute(HibernateCallbackT action) throws Da

Spring 使用的设计模式(一) CallBack(回调)
public <T> T execute(HibernateCallback<T> action) throws DataAccessException {return doExecute(action, false, false);}protected <T> T doExecute(HibernateCallback<T> action, boolean enforceNewSession, boolean enforceNativeSession)throws DataAccessException {Assert.notNull(action, "Callback object must not be null");Session session = (enforceNewSession ?SessionFactoryUtils.getNewSession(getSessionFactory(), getEntityInterceptor()) : getSession());boolean existingTransaction = (!enforceNewSession &&(!isAllowCreate() || 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 =(enforceNativeSession || isExposeNativeSession() ? session : createSessionProxy(session)); //在HibernateTemplate中得到实现,然后调用回调函数实现具体的逻辑T 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());}}}}

?由此可见,在此处使用回调模式,公共部分的操作都放在了hibernateTemplate的doExcute方法里,具体的实现让程序员来实现HibernateCallback回调接口,从而实现具体的逻辑,本人感觉这是CallBack模式的一大优点

?

热点排行