鹰翔宇空

学习和生活

BlogJava 首页 新随笔 联系 聚合 管理
  110 Posts :: 141 Stories :: 315 Comments :: 1 Trackbacks

原文引自:http://www.javaeye.com/pages/viewpage.action?pageId=1141

作者: 冰云
整理:robbin

原理:利用Hibernate3提供的PostLoadEventListener在loadHibernate实体类的时候触发PostLoadEvent事件,编写一个自定义的事件监听器,注入依赖的Spring Bean对象

SpringHibernateInjector
import org.hibernate.event.PostLoadEvent;
import org.hibernate.event.PostLoadEventListener;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.config.AutowireCapableBeanFactory;

public class SpringHibernateInjector implements PostLoadEventListener, BeanFactoryAware{

    AutowireCapableBeanFactory beanFactory;
   
    public void onPostLoad(PostLoadEvent event) {
        Object hibernateObject = event.getEntity();
        beanFactory.autowireBeanProperties(hibernateObject, AutowireCapableBeanFactory.AUTOWIRE_BY_NAME, false);   
    }

    public void setBeanFactory(BeanFactory factory)  {
        beanFactory = (AutowireCapableBeanFactory) factory;
    }

}
applicationContext.xml
<bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource">
            <ref bean="dataSource" />
        </property>
        <property name="mappingResources">
            <list>
                ...domains.hbm.xml here...
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">
                    org.hibernate.dialect.Oracle9Dialect
                </prop>
                <prop key="hibernate.query.substitutions">
                    true 1, false 0
                </prop>
                <prop key="hibernate.show_sql">false</prop>
            </props>
        </property>
       <property name="eventListeners">
          <map>
            <entry key="post-load">
              <!-- This hibernate interceptor allows us to use Spring to inject services
 into Hibernate managed domain objects -->   
              <bean class="yourpackage.SpringHibernateInjector"/>
            </entry>        
           </map>
    </property>
    </bean>

注:此方法来自于ThoughtWorksPerrynFowler,俺只是摘抄一下

posted on 2006-02-11 14:30 TrampEagle 阅读(594) 评论(0)  编辑  收藏 所属分类: hibernateSpring

只有注册用户登录后才能发表评论。


网站导航: