集成 Spring 和 Hibernate 3. 应用程序在创建 bean 时抛出异常

Integrating Spring and Hibernate 3. Application throws exception when creating the beans

下午好!我开始使用框架 Spring 和 Hibernate 研究依赖注入和控制反转以及数据持久性。我正在尝试使用 Spring 集成两者来控制由 Spring 监视的所有组件的 Hibernate SessionFactory 可以接收作为依赖 SessionFactory,Spring 控制 everything.Unfortunately 我不能为了实现这个目标,我得到以下异常:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'produtosController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private br.com.caelum.estoque.dao.ProdutoDAO br.com.caelum.estoque.controller.ProdutosController.produtoDAO; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'produtoHibernateDAO' defined in file [C:\Program Files\eclipse\apache-tomcat-8.0.15\wtpwebapps\fj27-projeto-spring\WEB-INF\classes\br\com\caelum\estoque\dao\ProdutoHibernateDAO.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.hibernate.SessionFactory]: : Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring/app-config.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring/app-config.xml]: Invocation of init method failed; nested exception is org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:298)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1148)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
org.springframework.beans.factory.support.AbstractBeanFactory.getObject(AbstractBeanFactory.java:293)
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:290)
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:191)
org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:636)
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:934)
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
org.springframework.web.servlet.FrameworkServlet.configureAndRefreshWebApplicationContext(FrameworkServlet.java:651)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:602)
org.springframework.web.servlet.FrameworkServlet.createWebApplicationContext(FrameworkServlet.java:665)
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext(FrameworkServlet.java:521)
org.springframework.web.servlet.FrameworkServlet.initServletBean(FrameworkServlet.java:462)
org.springframework.web.servlet.HttpServletBean.init(HttpServletBean.java:136)
javax.servlet.GenericServlet.init(GenericServlet.java:158)
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:610)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:537)
org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1085)
org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:658)
org.apache.coyote.http11.Http11NioProtocol$Http11ConnectionHandler.process(Http11NioProtocol.java:222)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1556)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1513)
java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.lang.Thread.run(Thread.java:745)

从他所说的无法创建 bean 到 "SessionFactory" 因此无法创建用于数据持久化的 beans,"DAOS"。我已经遇到这个问题一个星期了,我已经看到并审查了应用程序中的设置-config.xml,尝试了很多东西,我尝试了论坛但我尝试过的都没有用,现在我请求你的帮助。

这是我的项目文件:

产品控制器

    package br.com.caelum.estoque.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import br.com.caelum.estoque.dao.ProdutoDAO;
import br.com.caelum.estoque.model.Produto;

@Controller
@RequestMapping(value = "produtos")
public class ProdutosController {

    @Autowired
    @Qualifier("produtoHibernateDAO")
    private ProdutoDAO produtoDAO;

    @RequestMapping(value = "index")
    public String index() {
        return "produtos/index";
    }

    @RequestMapping(value = "listar", method = RequestMethod.GET)
    public ModelAndView listar() {
        ModelAndView modelAndView = new ModelAndView("produtos/lista");
        modelAndView.addObject(produtoDAO.listar());
        return modelAndView;
    }

    @RequestMapping(value = "mostrar/{id}", method = RequestMethod.GET)
    public ModelAndView mostrar(@PathVariable Long id) {
        ModelAndView modelAndView = new ModelAndView("produtos/mostrar");
        modelAndView.addObject(produtoDAO.buscarPorId(id));
        return modelAndView;
    }

    @RequestMapping(value = "form")
    public String form() {
        return "produtos/form";
    }

    @RequestMapping(value = "salvar", method = RequestMethod.POST)
    public String salvar(Produto produto) {
        produtoDAO.salvar(produto);     
        return "redirect:/produtos/listar";
    }
}

ProdutoHibernateDAO

package br.com.caelum.estoque.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import br.com.caelum.estoque.model.Produto;

@Repository
public class ProdutoHibernateDAO implements ProdutoDAO {

    private Session session;

    @Autowired
    public ProdutoHibernateDAO(SessionFactory factory) {
        session = factory.openSession();
    }

    public void salvar(Produto produto) {
        session.save(produto);
    }

    public void alterar(Produto produto) {
        session.update(produto);
    }

    public List<Produto> listar() {
        List<Produto> produtos = session.createQuery("from Produto").list();
        return produtos;
    }

    public Produto buscarPorId(Long id) {
        return (Produto) session.get(Produto.class, id);
    }
}

ProdutoDAO

package br.com.caelum.estoque.dao;

import java.util.List;

import br.com.caelum.estoque.model.Produto;

public interface ProdutoDAO {

    void salvar(Produto produto);
    void alterar(Produto produto);
    List<Produto> listar();
    Produto buscarPorId(Long id);
}

产品

package br.com.caelum.estoque.model;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

@Entity
public class Produto {

    @Id
    @GeneratedValue
    private Long id;
    private String descricao;
    private Integer quantidade;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getDescricao() {
        return descricao;
    }

    public void setDescricao(String descricao) {
        this.descricao = descricao;
    }

    public Integer getQuantidade() {
        return quantidade;
    }

    public void setQuantidade(Integer quantidade) {
        this.quantidade = quantidade;
    }
}

应用-config.xml

<?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:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">


    <!-- Configura aonde o Spring deve buscar por beans anotados -->
    <context:component-scan base-package="br.com.caelum.estoque" />

    <!-- Habilitar suporte a anotação @Controller -->
    <mvc:annotation-driven />

    <!-- Factory Bean para a SessionFactory do Hibernate. Utilizando esta factory 
        fazemos com que a SessionFactory do hibernate seja gerenciada pelo Spring. -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/fj21" />
        <property name="username" value="root" />
        <property name="password" value="m19731973f" />
    </bean>

    <!-- Configuração das propriedades do Hibernate -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
        <property name="dataSource" value="dataSource" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.connection.url">jdbc:mysql://localhost/fj21</prop>
                <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
                <prop key="hibernate.connection.username">root</prop>
                <prop key="hibernate.connection.password">m19731973f</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.connection.autocommit">true</prop>
            </props>
        </property>
        <property name="annotatedClasses">
            <list>
                <value>br.com.caelum.estoque.model.Produto</value>
            </list>
        </property>
    </bean>

</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    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"
    id="WebApp_ID" version="2.5">

    <display-name>FJ27 Estoque</display-name>

    <!-- Configura o Spring Servlet -->
    <servlet>
        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>
                    /WEB-INF/spring/app-config.xml
                </param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Spring MVC Dispatcher Servlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


</web-app>

aplicationContext.xml

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

</beans>

我试过这样改构造方法

@Autowired
public ProdutoHibernateDAO(SessionFactory factory) {
    session = factory.getCurrentSession();
}

和方法

public void salvar(Produto produto) {
    session.getSessionFactory().getCurrentSession().save(produto);
}

spring 和 hibernate 都在版本 4 中。

我解决了这个问题。我将 jarss Spring 作为 Hibernate 更改为版本 4(spring 4.1.4.RELEASE,hibernate 4.3.8.Final)。所以我更改了我的 app-config.xml 文件并让他这样:

<!-- Configuração das propriedades do Hibernate -->
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.connection.url">jdbc:mysql://localhost/fj21</prop>
                <prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
                <prop key="hibernate.connection.username">root</prop>
                <prop key="hibernate.connection.password">m19731973f</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
                <prop key="hibernate.connection.autocommit">true</prop>
            </props>
        </property>
        <property name="annotatedClasses">
            <list>
                <value>br.com.caelum.estoque.model.Produto</value>
            </list>
        </property>
    </bean>

我觉得应该是jar版本冲突。现在工作完美。 感谢大家的帮助。