0

STATUS: SOLVED. 没关系。发现了问题。entityManager 不应该在 dao 中自动装配。感谢您的努力。

我在 NetBeans 7.3 中使用 spring 3.2.3 和 hibernate 4.xx maven 新建了一个简单的 Web 项目。我在最后用以下代码说明了以下异常。

有没有人遇到过类似的问题或者知道为什么会这样。

控制器

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package web.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import web.entity.Users;
import web.service.UserService;

/**
 *
 * @author syncsys
 */
@Controller
public class UserController {
    @Autowired
    private UserService userService;

//    @RequestMapping(value = "/create", method = RequestMethod.GET )
    @RequestMapping(value = "/create" )
    public String creatUser(ModelMap model){
        Users user = new Users();
        user.setEmail("myemail@mydomain.com");
        user.setName("myname");
        userService.saveOrUpdate(user);    //////// this is line 29
        System.out.println("created--------------------");
        return "create";       
    }

package web.dao.impl.jpa;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.hibernate.Session;
import org.springframework.stereotype.Repository;
import web.dao.UserDAO;
import web.entity.Users;



/**
 * 
 * @version $Revision$
 * @since   1.0
 */
@Repository
public class UserDAOImpl implements UserDAO {

    /**
     * The JPA entity manager
     */

    @Autowired
    private EntityManager entityManager;

    /**
     * Set the entity manager
     * 
     * @param entityManager
     */
    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    /**
     * Helper method to return the hibernate session from the JPA
     * entity manager implementation.
     * 
     * @return the hibernate {#link Session}
     */
    protected Session getHibernateSession() {
        return entityManager.unwrap(Session.class);
    }

    /**
     * Saves or Updates an existing user entity instance.
     * 
     * @param user  the user entity
     * @return      the managed user entity instance
     */
    public void saveOrUpdate(Users user) {
        if(user.getId() == 0) {
            entityManager.persist(user);

        }
        else
            entityManager.merge(user);
    }

服务

package web.service;

/**
 *
 * @author syncsys
 */
import web.dao.UserDAO;
import web.entity.Users;

@Service
@Transactional(readOnly = true)
public class UserServiceImpl implements UserService{

    @Autowired
    private UserDAO userDAO;

    @Transactional(readOnly = false)
    public void saveOrUpdate(Users user){

         userDAO.saveOrUpdate(user);

    }
}

分派器-servlet.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:mvc="http://www.springframework.org/schema/mvc"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        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/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd"
>


    <context:component-scan base-package="web" >
    <context:include-filter type="annotation" expression="org.springframework.stereotype.Service"       />
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Repository"    />
    </context:component-scan> 
  <mvc:annotation-driven />
<!--  <context:annotation-config />-->
    <bean class="org.springframework.web.servlet.mvc.support.ControllerClassNameHandlerMapping"/>

    <!--
    Most controllers will use the ControllerClassNameHandlerMapping above, but
    for the index controller we are using ParameterizableViewController, so we must
    define an explicit mapping for it.
    -->
    <bean id="urlMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
        <property name="mappings">
            <props>
                <prop key="index.htm">indexController</prop>
            </props>
        </property>
    </bean>

    <bean id="viewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
          <property name="prefix" value="/WEB-INF/view/jsp/" />
            <property name="suffix" value=".jsp" />
    </bean>        

    <!--
    The index controller.
    -->
    <bean name="indexController"
          class="org.springframework.web.servlet.mvc.ParameterizableViewController">
          <property name="viewName" value="index" />
    </bean>



     <!---
     ##########################################################################
    Hibernate

    -->
<!--    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.postgresql.Driver" />
        <property name="url" value="${jdbc.url}jdbc:postgresql://localhost:5432/postgres" />
        <property name="username" value="postgres" />
        <property name="password" value="abc" />
    </bean>

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="packagesToScan" value="web.entity" />
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</prop>
            </props>

        </property>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

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

    ###########################################################
    -->


<!--

    JPA based instead of hibernate

-->
        <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<!-- 
        This configures the EntityManagerFactory object used for JPA/Spring managed persistent objects. 
     -->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml" />
        <property name="persistenceUnitName" value="persistence-unit-demo" /> 
        <property name="dataSource" ref="dataSource" />
                <property name="packagesToScan" value="web.entity" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                                <property name="database" value="POSTGRESQL" />
<!--    giving errors       <property name="databasePlatorm" value="org.hibernate.dialect.PostgreSQLDialect"/>-->
<!--                                <property name="database" value="HSQL" />-->
                <property name="showSql" value="true" />
                <property name="generateDdl" value="true" />                        
            </bean>
        </property>   
                <property name="jpaProperties">
                    <props>
                        <prop key="hibernate.hbm2ddl.auto">create-drop</prop>
                    </props>
                </property>                         
    </bean> 
    <bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
    <!-- Pulls database connection from the tomcat container's context database pool via JNDI -->
<!--    <jee:jndi-lookup id="dataSource" jndi-name="jdbc/mssqlserver" resource-ref="true"/>-->

        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" >
            <property name="driverClassName" value="org.postgresql.Driver" />
            <property name="url" value="jdbc:postgresql://localhost:5432/postgres" />
            <property name="username" value="postgres" />
            <property name="password" value="abc" />
        </bean>



    <!--
        Sets up our transaction manager. 
     -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
        <property name="jpaDialect" ref="jpaDialect" />
        <property name="dataSource" ref="dataSource" />
<!-- giving errors               <property name="loadTimeWeaver">
                    <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
                </property>-->
    </bean>

        <!--
        Defines our transaction manager for Transactional annotations.
     -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <bean id="sessionFactory" factory-bean="entityManagerFactory" factory-method="getSessionFactory" />


</beans>

Maven pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.tm.spring</groupId>
    <artifactId>ttmaven</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>ttmaven</name>


    <url>http://maven.apache.org</url>

    <properties>
        <spring.version>3.2.3.RELEASE</spring.version>
        <junit.version>4.11</junit.version>
        <jdk.version>1.6</jdk.version>
    </properties>

    <dependencies>
                <dependency>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-core</artifactId>
                    <version>4.2.3.Final</version>
                </dependency>

                <dependency>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-entitymanager</artifactId>
                    <version>4.2.3.Final</version>
                </dependency>

                <dependency>
                    <groupId>org.jumpmind.symmetric.jdbc</groupId>
                    <artifactId>postgresql</artifactId>
                    <version>9.2-1002-jdbc4</version> 
                </dependency>
            <!-- Java EE -->
                <dependency>
                    <groupId>javax.servlet</groupId>
                    <artifactId>jstl</artifactId>
                    <version>1.1.1</version>
                    <scope>runtime</scope>
                </dependency>

                <dependency>
                    <groupId>taglibs</groupId>
                    <artifactId>standard</artifactId>
                    <scope>runtime</scope>
                    <version>1.1.1</version>
                </dependency>

        <!-- Spring 3 dependencies -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>${spring.version}</version>
        </dependency>

                <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>${spring.version}</version>
        </dependency>

                <dependency>
                        <groupId>org.springframework</groupId>
                        <artifactId>spring-context</artifactId>
                        <version>${spring.version}</version>
                </dependency>

                <dependency>
                        <groupId>org.springframework</groupId>
                        <artifactId>spring-beans</artifactId>
                        <version>${spring.version}</version>
                </dependency>

                <dependency>
                        <groupId>org.springframework</groupId>
                        <artifactId>spring-aop</artifactId>
                        <version>${spring.version}</version>
                </dependency>
                <dependency>
                        <groupId>org.springframework</groupId>
                        <artifactId>spring-orm</artifactId>
                        <version>${spring.version}</version>
                </dependency>



        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>CounterWebApp</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.0</version>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

例外

描述 服务器遇到一个内部错误,阻止它完成这个请求。

例外

http://pastebin.com/KzzVH5c9 对于所有异常,因为它们太长并且超出了 stackoverflow 字符限制。

一些主要的是

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private web.service.UserService web.controller.UserController.userService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private web.dao.UserDAO web.service.UserServiceImpl.userDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.persistence.EntityManager web.dao.impl.jpa.UserDAOImpl.entityManager; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManager] 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)}

org.springframework.beans.factory.BeanCreationException: Could not autowire field: private web.service.UserService web.controller.UserController.userService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private web.dao.UserDAO web.service.UserServiceImpl.userDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.persistence.EntityManager web.dao.impl.jpa.UserDAOImpl.entityManager; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManager] 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)}

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private web.dao.UserDAO web.service.UserServiceImpl.userDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.persistence.EntityManager web.dao.impl.jpa.UserDAOImpl.entityManager; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManager] 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)}

org.springframework.beans.factory.BeanCreationException: Could not autowire field: private web.dao.UserDAO web.service.UserServiceImpl.userDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.persistence.EntityManager web.dao.impl.jpa.UserDAOImpl.entityManager; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManager] 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)}

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAOImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.persistence.EntityManager web.dao.impl.jpa.UserDAOImpl.entityManager; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManager] 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)}

org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.persistence.EntityManager web.dao.impl.jpa.UserDAOImpl.entityManager; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManager] 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)}

org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.persistence.EntityManager] 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

2 回答 2

0

entityManager 不应该在 dao 中使用 @Autowired。感谢您的努力。

于 2013-07-22T06:54:48.080 回答
0

似乎您没有将 UserService 注入控制器。

@Autowired
private UserService userService;
于 2013-07-22T05:29:44.180 回答