工作总结: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");

 

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页