发生的异常:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name ‘customerDaoImpl’ defined in file [E:\Java\apache\apache-tomcat-7.0.52\webapps\ssh_demo1\WEB-INF\classes\com\itheima\dao\CustomerDaoImpl.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: ‘sessionFactory’ or ‘hibernateTemplate’ is required
原因:
HibernateDaoSupport与HibernateTemplate和setSessionFactory在MVC的Dao的获取(使用)
示例:
@Repository
public class CustomerDaoImpl extends HibernateDaoSupport implements CustomerDao {
@Autowired
private HibernateTemplate hibernateTemplate;
// public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
// this.hibernateTemplate = hibernateTemplate;
// }
@Resource
public void setSessionFactory0(SessionFactory session){
super.setSessionFactory(session);
}
public void save(Customer customer) {
hibernateTemplate.save(customer);
}
}
方法1 :在这里如果要使用继承HibernateDaoSupport 的话就要添加一个sessionFactory
@Resource
public void setSessionFactory0(SessionFactory session){
super.setSessionFactory(session);
}
方法2: 如果不继承那么直接获取 前提 applicationContext.xml文件已经配置了hibernateTemplate并已经植入了sessionFactory
@Autowired
private HibernateTemplate hibernateTemplate;
即可或者添加一个set方法也可以
底层代码解释:
public abstract class HibernateDaoSupport extends DaoSupport {
private HibernateTemplate hibernateTemplate;
public final void setSessionFactory(SessionFactory sessionFactory) {
if (this.hibernateTemplate == null || sessionFactory != this.hibernateTemplate.getSessionFactory()) {
this.hibernateTemplate = this.createHibernateTemplate(sessionFactory);
}
}
因为HibernateDaoSupport需要一个sessionFactory或者hibernateTemplate 所以 要不然自动获取hibernateTemplate 要不然 给人家一个sessionFactory
纯属个人笔记欢迎大牛指点~~~