当前位置: 代码迷 >> Java Web开发 >> org.springframework.orm.hibernate3.LocalSessionFactoryBean的疑惑解决办法
  详细解决方案

org.springframework.orm.hibernate3.LocalSessionFactoryBean的疑惑解决办法

热度:551   发布时间:2016-04-17 10:53:30.0
org.springframework.orm.hibernate3.LocalSessionFactoryBean的疑惑
applicationContext中配置了sessionFactory  
 <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的代码 以及父类 和 接口 都没用继承 SessionFactoryImpl 
有知道的高手能解惑一下吗?

------解决方案--------------------
得到初步的答案了..具体还需要高人分析...

方便后人~~

LocalSessionFactoryBean实现了org.springframework.beans.factory.FactoryBean接口, spring在装配的时候, 如果发现实现了org.springframework.beans.factory.FactoryBean接口, 就会使用FactoryBean#getObject() 方法返回的对象装配,具体的可以看下文档.
如果你想拿到LocalSessionFactoryBean实例, 在id前面加个'&'就可以了,在你的配置文件中BeanFactory.getBean('&sessionFactory')拿到的就是LocalSessionFactoryBean的实例.
------解决方案--------------------
LocalSessionFactoryBean sessionFactory=(LocalSessionFactoryBean)appContext.getBean("sessionFactory")这段代码你换成:
ClassPathXmlApplicationContext cpx=new ClassPathXmlApplicationContext("applicationContext.xml");
//先找资源文件,再找Bean
LocalSessionFactoryBean sessionFactory=(LocalSessionFactoryBean)cpx.getBean("sessionFactory");
  相关解决方案