`
hz_chenwenbiao
  • 浏览: 1010540 次
  • 性别: Icon_minigender_1
  • 来自: 广州
社区版块
存档分类
最新评论

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

阅读更多

将ssh整合时,出现如下异常:

2010-11-11 15:34:59,765 [org.springframework.web.context.ContextLoader]-[ERROR] Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'postDaoImpl' defined in file [D:\OldWTBWorldSpace\.metadata\.me_tcat\webapps\mytieba\WEB-INF\classes\yellowb\dao\service\impl\PostDaoImpl.class]: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: 'sessionFactory' or 'hibernateTemplate' is required
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1338)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
	at java.security.AccessController.doPrivileged(Native Method)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:429)
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
	at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:255)
	at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:199)
	at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:45)
	at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3827)
	at org.apache.catalina.core.StandardContext.start(StandardContext.java:4334)
	at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
	at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
	at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:525)
	at org.apache.catalina.startup.HostConfig.deployDirectory(HostConfig.java:920)
	at org.apache.catalina.startup.HostConfig.deployDirectories(HostConfig.java:883)
	at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:492)
	at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1138)
	at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:311)
	at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:117)
	at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
	at org.apache.catalina.core.StandardHost.start(StandardHost.java:719)
	at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
	at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:443)
	at org.apache.catalina.core.StandardService.start(StandardService.java:516)
	at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
	at org.apache.catalina.startup.Catalina.start(Catalina.java:566)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:288)
	at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:413)
Caused by: java.lang.IllegalArgumentException: 'sessionFactory' or 'hibernateTemplate' is required
	at org.springframework.orm.hibernate3.support.HibernateDaoSupport.checkDaoConfig(HibernateDaoSupport.java:117)
	at org.springframework.dao.support.DaoSupport.afterPropertiesSet(DaoSupport.java:44)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1369)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1335)
	... 39 more
2010-11-11 15:34:59 org.apache.catalina.core.StandardContext listenerStart

 这里说少了sessionFactory或者是hibernateTemplate,这里是因为我在dao层里使用了HibernateDaoSupport来访问数据库,如其中一个类为:

package yellowb.dao.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.LockMode;
import org.hibernate.SessionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import yellowb.dao.service.PostDaoService;
import yellowb.entity.Post;

/**
 * A data access object (DAO) providing persistence and search support for Post
 * entities. Transaction control of the save(), update() and delete() operations
 * can directly support Spring container-managed transactions or they can be
 * augmented to handle user-managed Spring transactions. Each of these methods
 * provides additional information for how to configure it for the desired type
 * of transaction control.
 * 
 */
@Service
@Transactional
public class PostDaoImpl extends HibernateDaoSupport implements PostDaoService
{
	
	
	private static final Log log = LogFactory.getLog(PostDaoImpl.class);
	protected void initDao()
	{
		// do nothing
	}

	/* (non-Javadoc)
	 * @see yellowb.dao.impl.PostDAOService#save(yellowb.dao.impl.Post)
	 */
	public int save(Post transientInstance)
	{
		log.debug("saving Post instance");
		try
		{
			getHibernateTemplate().save(transientInstance);
			log.debug("save successful");
		} catch (RuntimeException re)
		{
			log.error("save failed", re);
			throw re;
		}
		return transientInstance.getId();
	}

	/* (non-Javadoc)
	 * @see yellowb.dao.impl.PostDAOService#delete(yellowb.dao.impl.Post)
	 */
	public void delete(Post persistentInstance)
	{
		log.debug("deleting Post instance");
		try
		{
			getHibernateTemplate().delete(persistentInstance);
			log.debug("delete successful");
		} catch (RuntimeException re)
		{
			log.error("delete failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see yellowb.dao.impl.PostDAOService#findById(java.lang.Integer)
	 */
	public Post findById(java.lang.Integer id)
	{
		log.debug("getting Post instance with id: " + id);
		try
		{
			Post instance = (Post) getHibernateTemplate().get(
					"yellowb.entity.Post", id);
			return instance;
		} catch (RuntimeException re)
		{
			log.error("get failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see yellowb.dao.impl.PostDAOService#findByExample(yellowb.dao.impl.Post)
	 */
	public List findByExample(Post instance)
	{
		log.debug("finding Post instance by example");
		try
		{
			List results = getHibernateTemplate().findByExample(instance);
			log.debug("find by example successful, result size: "
					+ results.size());
			return results;
		} catch (RuntimeException re)
		{
			log.error("find by example failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see yellowb.dao.impl.PostDAOService#findByProperty(java.lang.String, java.lang.Object)
	 */
	public List findByProperty(String propertyName, Object value)
	{
		log.debug("finding Post instance with property: " + propertyName
				+ ", value: " + value);
		try
		{
			String queryString = "from Post as model where model."
					+ propertyName + "= ?";
			return getHibernateTemplate().find(queryString, value);
		} catch (RuntimeException re)
		{
			log.error("find by property name failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see yellowb.dao.impl.PostDAOService#findByUserName(java.lang.Object)
	 */
	public List findByUserName(Object userName)
	{
		return findByProperty(USER_NAME, userName);
	}

	/* (non-Javadoc)
	 * @see yellowb.dao.impl.PostDAOService#findByTitle(java.lang.Object)
	 */
	public List findByTitle(Object title)
	{
		return findByProperty(TITLE, title);
	}

	/* (non-Javadoc)
	 * @see yellowb.dao.impl.PostDAOService#findByText(java.lang.Object)
	 */
	public List findByText(Object text)
	{
		return findByProperty(TEXT, text);
	}

	/* (non-Javadoc)
	 * @see yellowb.dao.impl.PostDAOService#findByTimes(java.lang.Object)
	 */
	public List findByTimes(Object times)
	{
		return findByProperty(TIMES, times);
	}

	/* (non-Javadoc)
	 * @see yellowb.dao.impl.PostDAOService#findByClicks(java.lang.Object)
	 */
	public List findByClicks(Object clicks)
	{
		return findByProperty(CLICKS, clicks);
	}

	/* (non-Javadoc)
	 * @see yellowb.dao.impl.PostDAOService#findAll()
	 */
	public List findAll()
	{
		log.debug("finding all Post instances");
		try
		{
			String queryString = "from Post";
			return getHibernateTemplate().find(queryString);
		} catch (RuntimeException re)
		{
			log.error("find all failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see yellowb.dao.impl.PostDAOService#merge(yellowb.dao.impl.Post)
	 */
	public Post merge(Post detachedInstance)
	{
		log.debug("merging Post instance");
		try
		{
			Post result = (Post) getHibernateTemplate().merge(detachedInstance);
			log.debug("merge successful");
			return result;
		} catch (RuntimeException re)
		{
			log.error("merge failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see yellowb.dao.impl.PostDAOService#attachDirty(yellowb.dao.impl.Post)
	 */
	public void attachDirty(Post instance)
	{
		log.debug("attaching dirty Post instance");
		try
		{
			getHibernateTemplate().saveOrUpdate(instance);
			log.debug("attach successful");
		} catch (RuntimeException re)
		{
			log.error("attach failed", re);
			throw re;
		}
	}

	/* (non-Javadoc)
	 * @see yellowb.dao.impl.PostDAOService#attachClean(yellowb.dao.impl.Post)
	 */
	public void attachClean(Post instance)
	{
		log.debug("attaching clean Post instance");
		try
		{
			getHibernateTemplate().lock(instance, LockMode.NONE);
			log.debug("attach successful");
		} catch (RuntimeException re)
		{
			log.error("attach failed", re);
			throw re;
		}
	}
	
	/* (non-Javadoc)
	 * @see yellowb.dao.impl.PostDAOService#getMaxTopicID()
	 */
	public int getMaxTopicID(){
		log.debug("find the max id of total post topics");
		return (Integer) getHibernateTemplate().find("select max(p.id) from Post as p").iterator().next();
	}
	
	/* (non-Javadoc)
	 * @see yellowb.dao.impl.PostDAOService#getMinTopicID()
	 */
	public int getMinTopicID(){
		log.debug("find the max id of total post topics");
		return (Integer) getHibernateTemplate().find("select min(p.id) from Post as p").iterator().next();
	}

	public static PostDaoService getFromApplicationContext(ApplicationContext ctx)
	{
		return (PostDaoService) ctx.getBean("PostDAO");
	}
}
 

我本以为要在这些类里加入sessionFactory就可以解决问题:

@Resource
	private org.hibernate.SessionFactory sessionFactory;

 但是没有,还是报这个错,后来看了网上的解决方式 ,原因是spring.xml中没有加上default-autowire="byName" ,在注解的时候找不到实例化的sessionFactory,而注入了一个空的,在hibernate检查的时候就报那个错了。

spring配置文件加入byName的方式注入bean后,就可以正确使用注解了:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-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"
           default-autowire="byName" default-lazy-init="true">

	<context:component-scan base-package="yellowb.dao.service" />
	<context:component-scan base-package="yellowb.service" />
	<aop:aspectj-autoproxy proxy-target-class="true" />

	<!-- 要用的数据库的访问操作,即要开启事务来处理业务时,下面的transactionManager就必须配置,而若只用spring那么可以直接配下一个"启动spring注解功能 " -->
	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

	<!--启动spring注解功能-->
	<tx:annotation-driven transaction-manager="transactionManager"
		proxy-target-class="true" />	

	<!-- 线程池配置 -->
	<bean id="taskExecutor"
		class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
		<property name="corePoolSize" value="3" />
		<property name="keepAliveSeconds" value="200" />
		<property name="maxPoolSize" value="5" />
		<property name="queueCapacity" value="25" />
	</bean>

<!--  缓存管理  -->
	<bean id="cacheManager"
		class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
		<property name="configLocation">
			<value>classpath:ehcache.xml</value>
		</property>
	</bean>
	
	<!-- 下面应该是表示使用AnnotationConfiguration配置和生成SessionFactory,并且要指明hibernate配置文件的位置 -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean" >
		<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
		<!-- 下面的是进行hibernate的依赖注入的配置方式 -->
<!--   
		<property name="configurationClass" value="org.hibernate.cfg.AnnotationConfiguration" />
		<property name="configLocation">
			<value>classpath:hibernate.cfg.xml</value>
		</property>
-->
	</bean>

	<!-- 在此进行自动代理配置 -->
	<bean id="beanNameAutoProxyCreator"
		class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
		<property name="proxyTargetClass" value="true" />
		<property name="beanNames">
			<list>
				<value>*Impl</value>
			</list>
		</property>
	</bean>
	
</beans>
 

 

分享到:
评论

相关推荐

    ssh 框架完全整合笔记

    SSH框架整合是将Spring、Struts和Hibernate三个流行的开源Java Web开发框架集成在一起,以构建高效、可维护的Web应用程序。下面将详细讲解SSH框架整合的各个部分。 一、Spring整合Hibernate 1. **无需Hibernate...

    java程序员ssh面试常见题

    ### Java程序员SSH面试常见题详解 #### 1. Action是什么?如何证明Action是线程安全的? - **知识点概述**:在Struts框架中,Action是处理用户请求的核心组件之一,它负责执行业务逻辑并返回相应的结果。由于...

    SSH框架面试题.pdf

    SSH框架可以通过Spring的`&lt;aop:config&gt;`和`&lt;aop:pointcut&gt;`配置异常通知来处理异常。此外,还可以通过Struts的异常处理机制来捕获和处理Action层中的异常。 37. **如何确保SSH框架中的性能优化?** 性能优化可以...

    SSH框架配置流程文档实例教程

    在IT行业中,SSH框架是三个非常著名的开源Java框架的组合,包括Struts、Hibernate和Spring。它们各自负责不同的功能,Struts用于控制应用程序的流程,Hibernate处理数据持久化,而Spring则提供全面的依赖注入和面向...

    spring+hibernate

    通常,这样的资料会涵盖Spring的ApplicationContext配置、Hibernate的SessionFactory配置、两者的整合方式,如使用HibernateTemplate或JPA,以及如何在Spring MVC中处理数据请求等。 学习Spring和Hibernate的整合,...

    SpringMVC-SSH全注解

    &lt;bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate"&gt; &lt;property name="sessionFactory" ref="sessionFactory" /&gt; class="org.springframework.orm.hibernate3....

    ssh(structs,spring,hibernate)框架中的上传下载

     本文将围绕SSH文件上传下载的主题,向您详细讲述如何开发基于SSH的Web程序。SSH各框架的均为当前最新版本:  •Struts 1.2  •Spring 1.2.5  •Hibernate 3.0  本文选用的数据库为Oracle 9i,当然你可以在不...

    struts+hibernate,spring面试题

    在Spring中使用Hibernate,通常需要配置SessionFactory、TransactionManager,使用HibernateTemplate或SessionFactoryBean进行数据访问,同时结合Spring的声明式事务管理,确保事务的正确性和一致性。 以上是对SSH...

    HibernateDaoSupport与JdbcDaoSupport

    **HibernateDaoSupport**主要用于整合Hibernate框架,提供了一种更加简洁的方式来使用Hibernate进行数据库操作。而**JdbcDaoSupport**则主要针对原生JDBC操作进行了封装,使得开发者能够更方便地执行SQL语句。 ####...

    struts spring hibernate面试题

    - **集成方法**:在 Spring 中,可以通过 `SessionFactory` 和 `HibernateTemplate` 或 `JpaTemplate` 简化 Hibernate 的使用。`SessionFactory` 提供了创建 Session 的工厂,而 `HibernateTemplate` 或 `...

    struts2+hirbate+spring面试题

    Struts2、Spring和Hibernate(SSH)是Java企业级开发中的三大主流框架,它们共同构建了一个强大的MVC(模型-视图-控制器)架构。在面试中,掌握这些框架的基本概念、工作原理以及最佳实践至关重要,尤其是对于刚踏入...

Global site tag (gtag.js) - Google Analytics