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>
 

 

你可能感兴趣的:(java,DAO,apache,spring,ssh)