工作總結:org.springframework.orm.hibernate3.LocalSessionFactoryBean的疑惑解決辦法

使用xml 配置的hibernate配置信息後,事例如下:

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="dataSource" ref="dataSource"></property>
  <property name="hibernateProperties">
  <props>
  <prop key="hibernate.dialect" >org.hibernate.dialect.SQLServerDialect</prop>
  <prop key="hibernate.jdbc.batch_size">20</prop>
  <prop key="hibernate.show_sql">true</prop>
  </props>
  </property>
  <property name="mappingResources">
  <list>
  <value>com/jw/pojo/JwUser.hbm.xml</value>
  </list>
  </property>
  </bean>

在junit4中定義了一個測試

@Test
public void beanSessionFactoryTest(){
  LocalSessionFactoryBean sessionFactory=(LocalSessionFactoryBean)appContext.getBean("sessionFactory");
}

運行測試的時候報了一個異常

Testcase: beanSessionFactoryTest(com.test.spring.SpringBeanTest): Caused an ERROR
org.hibernate.impl.SessionFactoryImpl cannot be cast to org.springframework.orm.hibernate3.LocalSessionFactoryBean
java.lang.ClassCastException: org.hibernate.impl.SessionFactoryImpl cannot be cast to org.springframework.orm.hibernate3.LocalSessionFactoryBean

問題分析:

  LocalSessionFactoryBean實現了org.springframework.beans.factory.FactoryBean接口, spring在裝配的時候, 如果發現實現了org.springframework.beans.factory.FactoryBean接口, 就會使用FactoryBean#getObject() 方法返回的對象裝配,具體的可以看下文檔.
  如果你想拿到LocalSessionFactoryBean實例, 在id前面加個'&'就可以了,在你的配置文件中BeanFactory.getBean('&sessionFactory')拿到的就是LocalSessionFactoryBean的實例.

解決方法:

1、取真實的LocalSessionFactoryBean 實例對象

ClassPathXmlApplicationContext cpx=new ClassPathXmlApplicationContext("beans.xml");
LocalSessionFactoryBean sessionFactory=(LocalSessionFactoryBean)cpx.getBean("&sessionFactory");
System.out.println("step3 sessionFactory=" + sessionFactory );

2、取SessionFactoryImpl 對象(即Hibernate的SessionFactory的具體實現類)

 SessionFactoryImpl sessionFactoryImpl = (SessionFactoryImpl) applicationContext.getBean("sessionFactory");

 

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