天天看點

SSH整合,"sessionFactory " or "hibernateTemplate " is required異常

首先遇到的問題就是HibernateDaoSupport引起的,程式中所有的DAO都繼承自HibernateDaoSupport,而HibernateDaoSupport需要注入sessionfactory或者hibernateTemplate,是以出現"sessionFactory " or "hibernateTemplate " is required異常,但是在spring配置檔案中加入sessionFactory的bean配置以後,仍然出現異常。

後來看了網上的解決方式 ,原因是spring.xml中沒有加上default-autowire="byName" ,在注解的時候找不到執行個體化的sessionFactory,而注入了一個空的,在hibernate檢查的時候就報那個錯了。spring配置檔案加入byName的方式注入bean後,就可以正确使用注解了

<beans

    xmlns="http://www.springframework.org/schema/beans"

    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

       xmlns:aop="http://www.springframework.org/schema/aop"   

    xmlns:tx="http://www.springframework.org/schema/tx" 

    xmlns:context="http://www.springframework.org/schema/context"  

    xsi:schemaLocation="    

                http://www.springframework.org/schema/beans     

                http://www.springframework.org/schema/beans/spring-beans-2.5.xsd    

                http://www.springframework.org/schema/aop     

                http://www.springframework.org/schema/aop/spring-aop-2.5.xsd    

                http://www.springframework.org/schema/tx     

                http://www.springframework.org/schema/tx/spring-tx-2.5.xsd

                http://www.springframework.org/schema/context

                http://www.springframework.org/schema/context/spring-context-2.5.xsd"

                 default-autowire="byName" default-lazy-init="true">

總的原因就是缺少了這句default-autowire="byName"。這個鳥問題困惑了一下午

開始在沒添加default-autowire="byName"的時候,我添加了如下代碼就可以,不過這個隻是使得找到問題出現的原因,并不是解決的最終方法,最終解決方法還是添加了上面的一句到配置檔案中。

import com.yhqxgl.dao.TDeptDao;

import com.yhqxgl.entity.TDept;

@Repository("tDeptDaoImpl")

@Transactional

public class TDeptDaoImpl extends HibernateDaoSupport implements TDeptDao {

 public boolean add(TDept dept) {

  this.getHibernateTemplate().save(dept);

  return true;

 }

 @Autowired

    public void setSessionFactoryOverride(SessionFactory sessionFactory)

    {  

      super.setSessionFactory(sessionFactory);  

    }

}

相當sessionFactory還沒注入到HibernateDaoSupport中,使得這裡的this.getHibernateTemplate()=null。