各位大侠:
小弟最近在研究一个SSH构架开发,结果遇到了一个奇怪的问题.就是在用Spring管理Hibernate的时候,找不到sessionFactory。JeUseranswerDAO注入不进去。以下是部分源代码(由于篇幅有限,只能贴这么多)还请大家指教:
applicationContext.xml(部分代码):
<!-- sessionFactory读取hibernate的配置文件 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation"
value="classpath:hibernate.cfg.xml">
</property>
</bean>
   
<!-- 事件管理 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<!-- DAO文件 -->
<bean id="JeUseranswerDAO"
class="com.acshop.model.DAO.System.JeUseranswerDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>

</bean>
<!-- action -->
<bean id="AbstractFront" class="com.acshop.action.system.core.BasicFrontAction"
abstract="true">
<property name="ansDao" ref="JeUseranswerDAO"></property>
</bean>
......hibernate.cfg.xml 部分内容
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd"><hibernate-configuration>
<session-factory>
<property name="connection.username">root</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/eshopdb?characterEncoding=utf-8
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="connection.password"></property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.autoReconnect">true</property>
<property name="connection.autoReconnectForPools">
true
</property>
<property name="connection.is-connection-validation-required">
true
</property> <property name="show_sql">true</property>
<mapping resource="com/acshop/model/JeUserAnswer/answer/JeUseranswer.hbm.xml" />
<!-- 中间省略 -->
</session-factory></hibernate-configuration>BaseHibernateDAO.javapackage com.acshop;import java.util.List;
import org.hibernate.Session;public class BaseHibernateDAO implements IBaseHibernateDAO { public BaseHibernateDAO() {
} public int getAllRowCount(String hql) {
return 0;
} public List queryForPage(String hql, int offset, int length) {
return null;
} public Session getSession() {
return HibernateSessionFactory.getSession(); // 用HibernateSeesionFactory来管理和建立sessionFactory. 这里我没有用HibernateDaoSupport
}
}HibernateSessionFactory.java package com.acshop;import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;public class HibernateSessionFactory { private static String CONFIG_FILE_LOCATION;
private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
private static Configuration configuration;
private static SessionFactory sessionFactory;
private static String configFile; private HibernateSessionFactory() {
} public static Session getSession() throws HibernateException { //得到Session
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null)
rebuildSessionFactory();
session = sessionFactory == null ? null
: ((Session) (sessionFactory.openSession()));
threadLocal.set(session);
}
return session;
} public static void rebuildSessionFactory() { //重建Session
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
} public static void closeSession() throws HibernateException { //关闭Session
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null)
session.close();
} public static SessionFactory getSessionFactory() { //得到SessionFacotroy
return sessionFactory;
} public static void setConfigFile(String configFile) { //设置配置文件
configFile = configFile;
sessionFactory = null;
} public static Configuration getConfiguration() {//得到配置
return configuration;
} static {
CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
configuration = new Configuration();
configFile = CONFIG_FILE_LOCATION;
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();//初始化建立SessionFacotry
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
}
JeUseranswerDAO.java部分代码package com.acshop.model.DAO.System;import java.util.List;import org.apache.log4j.Logger;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.criterion.Example;import com.acshop.BaseHibernateDAO;
import com.acshop.model.JeUserAnswer.answer.JeUseranswer;public class JeUseranswerDAO extends BaseHibernateDAO //继承BaseHibernateDAO
{    private static final Logger logger = Logger.getLogger(JeUseranswerDAO.class);
    public static final String USER_ID = "userId";
    public static final String CLASS_ID = "classId";
    public static final String RESULT_NUM = "resultNum";
    public static final String TEACH_ID = "teachId";
    public static final String CONTEXT = "context";    public JeUseranswerDAO()
    {
    }    public void save(JeUseranswer transientInstance)
    {
        logger.debug("saving JeUseranswer instance");
        try
        {
            getSession().save(transientInstance);
            logger.debug("save successful");
        }
        catch(RuntimeException re)
        {
            logger.error("save failed", re);
            throw re;
        }
    }    public void delete(JeUseranswer persistentInstance)
    {
        logger.debug("deleting JeUseranswer instance");
        try
        {
            getSession().delete(persistentInstance);
            logger.debug("delete successful");
        }
        catch(RuntimeException re)
        {
            logger.error("delete failed", re);
            throw re;
        }
    }    public JeUseranswer findById(Integer id)
    {
        logger.debug((new StringBuilder("getting JeUseranswer instance with id: ")).append(id).toString());
        try
        {
            JeUseranswer instance = (JeUseranswer)getSession().get("com.acshop.model.JeUserAnswer.answer.JeUseranswer", id);
            return instance;
        }
        catch(RuntimeException re)
        {
            logger.error("get failed", re);
            throw re;
        }
    }}corebases.java 部分代码
package com.acshop.action.system.core;import java.util.List;import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import com.acshop.model.DAO.System.JeUseranswerDAO;import com.opensymphony.xwork2.ActionSupport;public class corebasic extends ActionSupport {
public JeUseranswerDAO ansDao;
public corebasic() {
installDir = "front";
page = 1;
substr = "yang";
pageContentNum = Integer.valueOf(1);
logger = Logger.getLogger(corebasic.class);
} public JeUseranswerDAO getAnsDao() { // ansDao的get方法
return ansDao;
} public void setAnsDao(JeUseranswerDAO ansDao) {// ansDao的set方法
this.ansDao = ansDao;
}
//这里我加了相应的set/get方法
}异常:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'JeUseranswerDAO' defined in file [D:\tomcat\webapps\acshop\WEB-INF\classes\applicationContext-default.xml]: Initialization of bean failed; nested exception is org.springframework.beans.InvalidPropertyException: Invalid property 'sessionFactory' of bean class [com.acshop.model.DAO.System.JeUseranswerDAO]: No property 'sessionFactory' found请问是怎么回事啊?? 

解决方案 »

  1.   

    它是说JeUseranswerDAO类中美有sessionFactory这个属性!
    你可以试着看一下在该类中能找到sessionFactory的属性吗?
      

  2.   

    <bean id="JeUseranswerDAO"
    class="com.acshop.model.DAO.System.JeUseranswerDAO">
    <property name="sessionFactory">
    <ref bean="sessionFactory" />
    </property>
    配置错误<property name="sessionFactory" ref ="sessionFactory">
    正解
      

  3.   

    还有如果是用到了spring的依赖注入时,
    ansDao可以不要get方法
      

  4.   

    bean id="JeUseranswerDAO"
    class="com.acshop.model.DAO.System.JeUseranswerDAO">
    <property name="sessionFactory">
    <ref bean="sessionFactory" />
    </property>
    </bean>
    JeUseranswerDAO 里没有定义setSessionFactory(SessionFactory s)方法,却向里面注入,所以抱错
      

  5.   

    可以用bean吧!
    bean和local在这时没有区别撒
    你直接用ref 还不是默认的事bean吗?
      

  6.   

       <bean id="JeUseranswerDAO"
    class="com.acshop.model.DAO.System.JeUseranswerDAO">
    <property name="sessionFactory">
    <ref bean="sessionFactory" />
    </property>
    </bean>
    在  JeUseranswerDAO 这个 类里面 提供 sessionFactory get set 方法 
      

  7.   

    他继承的IBaseHibernateDAO类中 ,难道没有sessionFactory属性的getset方法吗?
      

  8.   

    Spring 配置文件中
    <!-- DAO文件 -->
    <bean id="JeUseranswerDAO"
    class="com.acshop.model.DAO.System.JeUseranswerDAO">
    <property name="sessionFactory">
    <ref bean="sessionFactory" />
    </property>

    </bean>
    你这个sessionFactory 属性哪里来的,如果要spring支持Hibernate自动创建sessionFactory,要使实dao类extends HibernateDaoSupport才可以,这样话,你的spring就配置完整了
      

  9.   

    不行,不信你试试!  随便找个项目的spring配置文件,你把XXXDao注入的信息改成类似
    bean id="xxxDAO"
    class="com.acshop.model.DAO.System.xxxDAO">
    <property name="sessionFactory">
    <ref bean="sessionFactory" />
    </property>
    </bean>
    就不好使了,你按Alt+?  提示都没有证明没有这么用的!
      

  10.   

    JeUseranswerDAO的父类BaseHibernateDAO里面有get和set方法呢
      

  11.   

    顶,JeUseranswerDAO 也没有sessionFactory 属性。
      

  12.   

    也可能我说错了,呵呵!有时候这么用就错,改成我那样就好了!所以我不用ref bean
      

  13.   

    这个sessionFactory的配置在这里
    <bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
    <property name="configLocation"
    value="classpath:hibernate.cfg.xml">
    </property>
    </bean>