0

我已经集成了 Spring 和 Hibernate,当我使用 maven 的 jetty 插件运行我的应用程序时,Hibernate 创建了表,但我的 sessionFactory 对象为空,

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

<welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
</welcome-file-list>
<!-- The definition of the Root Spring Container shared by all Servlets 
    and Filters -->
<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value></param-value>
</context-param>

<!-- Creates the Spring Container shared by all Servlets and Filters -->
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- Processes application requests -->
<servlet>
    <servlet-name>appServlet</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring/appServlet/servlet-context.xml,
            /WEB-INF/spring/security-context.xml
            </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>appServlet</servlet-name>
    <url-pattern>/</url-pattern>
</servlet-mapping>

servlet-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
xmlns:p="http://www.springframework.org/schema/p" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<!-- DispatcherServlet Context: defines this servlet's request-processing 
    infrastructure -->

<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />

<!-- Handles HTTP GET requests for /resources/** by efficiently serving 
    up static resources in the ${webappRoot}/resources directory -->
<resources mapping="/resources/**" location="/resources/" />

<!-- Resolves views selected for rendering by @Controllers to .jsp resources 
    in the /WEB-INF/views directory -->
<beans:bean
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <beans:property name="prefix" value="/WEB-INF/views/" />
    <beans:property name="suffix" value=".jsp" />
</beans:bean>

<context:component-scan base-package="com.fyp.ptma" />



<beans:bean id="propertyConfigurer"
    class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
    p:location="/WEB-INF/jdbc.properties" />

<beans:bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close" p:driverClassName="${jdbc.driverClassName}"
    p:url="${jdbc.databaseurl}" p:username="${jdbc.username}" p:password="${jdbc.password}" />


<beans:bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <beans:property name="dataSource" ref="dataSource"></beans:property>
    <beans:qualifier value="sessionFactory"></beans:qualifier>
    <beans:property name="annotatedClasses">
        <beans:list>
            <beans:value>com.fyp.ptma.model.Application</beans:value>
            <beans:value>com.fyp.ptma.model.ApplicationVersion</beans:value>
            <beans:value>com.fyp.ptma.model.Defect</beans:value>
            <beans:value>com.fyp.ptma.model.DefectDetail</beans:value>
            <beans:value>com.fyp.ptma.model.Group</beans:value>
            <beans:value>com.fyp.ptma.model.Downloader</beans:value>
            <beans:value>com.fyp.ptma.model.Notification</beans:value>
            <beans:value>com.fyp.ptma.model.RegisterStatus</beans:value>
            <beans:value>com.fyp.ptma.model.User</beans:value>
            <beans:value>com.fyp.ptma.model.Invitation</beans:value>
            <beans:value>com.fyp.ptma.model.Installation</beans:value>
        </beans:list>
    </beans:property>
    <beans:property name="hibernateProperties">
        <beans:props>
            <beans:prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect
            </beans:prop>
            <beans:prop key="hibernate.show_sql">true</beans:prop>
            <beans:prop key="hibernate.hbm2ddl.auto">create</beans:prop>
        </beans:props>
    </beans:property>
</beans:bean>



<beans:bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <beans:property name="sessionFactory" ref="sessionFactory" />
</beans:bean>

用户道.java

@Repository
public class UserDao implements IUserDao {

@Autowired
@Qualifier(value="sessionFactory")
private SessionFactory sessionFactory;

public Session openSession() {
    return sessionFactory.getCurrentSession();
}

public Long save(Object objToSave) throws PersistenceException,
        ConstraintViolationException {
    Session session = null;
    try {
        session = this.openSession();
        session.beginTransaction();
        session.save(objToSave);
        session.getTransaction().commit();

    } catch (Exception e) {
        e.printStackTrace();
        session.getTransaction().rollback();
    } finally {
        // session.close();
    }

    return null;
}

public Long update(Object objToUpdate) throws PersistenceException {
    // TODO Auto-generated method stub
    return null;
}

public boolean delete(Object objToDelete) throws PersistenceException,
        ConstraintViolationException {
    // TODO Auto-generated method stub
    return false;
}

public List<Application> getAllApplications(User user)
        throws HibernateException {
    // TODO Auto-generated method stub
    return null;
}

public Application getApplication(User user) throws HibernateException {
    // TODO Auto-generated method stub
    return null;
}

public boolean authenticateLogin(User user) throws AuthenticationException,
        HibernateException {

    Session session = this.openSession();

    session.beginTransaction();
    Criteria criteria = session.createCriteria(User.class);
    criteria.add(Restrictions.eq("email", user.getEmail()));

    User userDB = (User) criteria.uniqueResult();

    return userDB.getPassword().equals(user.getPassword());

}

public User getUserByEmail(String email) throws HibernateException {
    Session session = this.openSession();
    session.beginTransaction();
    Criteria criteria = session.createCriteria(User.class);
    criteria.add(Restrictions.eq("email", email));

    User userDB = (User) criteria.uniqueResult();
    // session.close();
    return userDB;
}

}

我的控制器

@ResponseBody
@RequestMapping(value = "/processRegistration.html", method = RequestMethod.POST)
public String processRegistration(@ModelAttribute("user") User user,
        Model model, BindingResult result) {

    UserDao uDao = DaoFactory.getUserDao();
    uDao.save(user);

    return "ok";
}

当我在我的控制器中调用 uDao.save 时,UserDao 的 sessionFactory 对象为空,但是在初始化期间,当我尝试使用以下行的控制器时,我没有收到任何接线错误,

ApplicationContext context = new AnnotationConfigApplicationContext("com.fyp.ptma.dao");

它在提交表单时抛出异常:

: No matching bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
4

1 回答 1

0

这很愚蠢,但我正在做的是AutoWired我的 SessionFactory,Dao Class但是当我从我那里得到 Dao 时,Dao Factory我以 return new 的形式返回,Dao();这导致创建了全新的对象,因为SessionFactory是 Dao 中的实例变量,它的默认值Objectnull在这里,下面是我的错误剪断

public class UserDao{

@AutoWired
private SessionFactory sessionFactory;

...
//more code

}


public static Dao getUserDao() {
  return new UserDao();
}
于 2013-06-16T07:47:01.823 回答