entitymanager在DAO类上为null

时间:2011-06-27 03:21:24

标签: spring eclipselink

我正在尝试实现Spring MVC 3 + EclipseLink JPA 2 当我调用saveUser时,它会返回

  

NullPointerException,EntityManager是   空

public class UserDAO {
  @PersistenceContext
  private EntityManager em;
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

     @Transactional
    public User saveUser(User user){
        return em.merge(user);
    }

我的配置是:

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
    <property name="entityManagerFactory" ref="entityManagerFactory" />
     <property name="dataSource" ref="dataSource"></property>       
</bean>

<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="persistenceUnitName" value="application" />
    <property name="jpaVendorAdapter">
        <bean
            class="org.springframework.orm.jpa.vendor.EclipseLinkJpaVendorAdapter">
            <property name="showSql" value="true" />
            <property name="databasePlatform" value="org.eclipse.persistence.platform.database.MySQLPlatform" />

            <property name="generateDdl" value="false" />
        </bean>
    </property>
    <property name="loadTimeWeaver">
        <bean
            class="org.springframework.instrument.classloading.SimpleLoadTimeWeaver" />
    </property>
</bean>
<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="username" value=".." />
    <property name="password" value=".." />
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url"
        value="jdbc:mysql://..." />
</bean>

也有

    <context:component-scan base-package="com.elasticbeanstalk.mypackage" />
<context:annotation-config />

它在Tomcat启动期间初始化JPA。我为什么看到NPE?我可以错过什么吗?

1 个答案:

答案 0 :(得分:5)

如果手动实例化UserDAO,Spring将不会注入任何内容。如果DAO位于base-package <context:component-scan ../>下的软件包中,那么您只需将其自动装入Controller即可。如果没有,可以修改base-package,也可以手动在appcontext中定义DAO,然后也可以自动装配。