【问题标题】:JPA is not AutowiringJPA 不是自动装配
【发布时间】:2012-02-09 20:27:42
【问题描述】:

当我尝试自动装配我的 DAO 对象时,我得到一个空指针异常。给你看代码(我用的是maven + hibernate + spring + jpa):

@Repository
public class DAOFriendImp implements DAOFriend{

    private EntityManagerFactory emf = Persistence.createEntityManagerFactory("persistence");
    private EntityManager entityManager = emf.createEntityManager();

    @PersistenceContext(unitName = "persistence")
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    public boolean save(Person person, Person friend) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public List<Person> getAllFriendOfPersonWithId(int id) {
        Person person = entityManager.find(Person.class, id);
        return person.getFriends();
    }

    @Override
    public boolean delete(Person person, Person friend) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

}

如您所见,我正在手动初始化我的 entityManager。那是因为如果我使用 persistenceContext 我也会得到一个空指针异常。也许是因为 DAOFriendImp 没有正确获得自动装配?我真的不知道。

现在让我告诉你我从哪里得到空指针:

public class FriendListLogic {

@Autowired
DAOFriendImp dao;

public List<Person> getEntrys(int userId) {
    List<Person> result = dao.getAllFriendOfPersonWithId(userId); //here
    return result;
}
}

我不知道为什么它没有被注入!配置 XML 中的一切似乎都很好。我将添加其余文件(pom、持久性、applicationcontext 和 servlet.xml)

Persistence.xml:

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence   http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd"
    version="1.0">

<persistence-unit name="persistence" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>com.divux.onex.model.Person</class>
    <class>com.divux.onex.model.CircleOfConnection</class>
    <properties>
        <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
        <property name="javax.persistence.jdbc.driver"   value="com.mysql.jdbc.Driver"   />
        <property name="javax.persistence.jdbc.url"        value="jdbc:mysql://localhost:3306/onex" />
        <property name="javax.persistence.jdbc.user"     value="root" />
        <property name="javax.persistence.jdbc.password" value="bterra" />
    </properties>
</persistence-unit>
</persistence>

注意:我在这里有我的 jdbc 用户密码驱动程序和 url,因为我在 applicationContext 中的 dataSource bean 中遇到了问题......如果我在那里有这些信息,它就不起作用(不知道为什么)

applicationContext.xml

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

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

<context:annotation-config />
<bean  class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> 
<bean id="dataSource"  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
</bean>

<bean id="entityManagerFactory"   class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="persistenceUnitName" value="persistence" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="database" value="MYSQL" />
            <property name="showSql" value="false" /> 
            <property name="generateDdl" value="false" />
            <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"  />
        </bean>
    </property>
    <property name="loadTimeWeaver">  
        <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"></bean>  
    </property>
</bean>

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

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"></bean>  

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


</beans>

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

<context:component-scan base-package="com.divux.onex.controller"></context:component-scan>
<context:component-scan base-package="com.divux.onex.daoImp"></context:component-scan>

<context:property-placeholder location="classpath*:resources/properties/*.properties"/>

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

<mvc:annotation-driven/>
<mvc:view-controller path="/" view-name="index"/>
<mvc:resources mapping="/resources/**" location="/resources/"/>

  <import resource="applicationContext.xml" />

</beans>

最后是 pom.xml(只是其中的一部分)

<properties>
    <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <org.springframework.version>3.0.5.RELEASE</org.springframework.version>
    <aspectj.version>1.6.11</aspectj.version>
    <org.slf4j-version>1.5.8</org.slf4j-version>
    <hibernate.version>3.6.7.Final</hibernate.version>
    <hibernate-search.version>4.0.0.Final</hibernate-search.version>
</properties>
<!-- JPA with Hibernate Persistence -->             
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.16</version>
    </dependency>
   <!-- Persistance -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-core</artifactId>
        <version>${hibernate.version}</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-entitymanager</artifactId>
        <version>${hibernate.version}</version>
        <exclusions>
            <exclusion>
                <groupId>cglib</groupId>
                <artifactId>cglib</artifactId>
            </exclusion>
            <exclusion>
                <groupId>dom4j</groupId>
                <artifactId>dom4j</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-ehcache</artifactId>
        <version>${hibernate.version}</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-search</artifactId>
        <version>${hibernate-search.version}</version>
    </dependency>
<!-- <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-jmx</artifactId> 
<version>${hibernate-jmx.version}</version> </dependency> -->
    <dependency>
        <groupId>org.hibernate.javax.persistence</groupId>
        <artifactId>hibernate-jpa-2.0-api</artifactId>
        <version>1.0.0.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-jpamodelgen</artifactId>
        <version>1.1.1.Final</version>
        <scope>provided</scope>
<!-- only need at compile time -->
    </dependency>
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib-nodep</artifactId>
        <version>2.2</version>
    </dependency>
    <dependency>
        <groupId>javax.transaction</groupId>
        <artifactId>jta</artifactId>
        <version>1.1</version>
    </dependency>


<!-- validation -->
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>4.1.0.Final</version>
        <exclusions>
            <exclusion>
                <groupId>javax.xml.bind</groupId>
                <artifactId>jaxb-api</artifactId>
            </exclusion>
            <exclusion>
                <groupId>com.sun.xml.bind</groupId>
                <artifactId>jaxb-impl</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
        <version>1.0.0.GA</version>
    </dependency>

<!-- AspectJ -->
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjrt</artifactId>
        <version>${aspectj.version}</version>
    </dependency>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>${aspectj.version}</version>
    </dependency>

</dependencies>

如果您需要更多信息,请告诉我!我不会添加错误输出,因为我认为这是不必要的。如果你需要它让我知道。

【问题讨论】:

  • 请您发布显示 NPE 的堆栈跟踪。
  • 我不知道如何获取该信息@Alex!你能告诉我怎么做吗?
  • 我认为PersistenceAnnotationBeanPostProcessorAutowiredAnnotationBeanPostProcessor不应该在上下文中明确提及:它们应该由XML指令自动添加。我可能错了,但添加它们是不正常的。
  • @BrunoX 我认为你应该添加错误输出
  • 自动装配不是由 JPA 完成的...

标签: hibernate spring jpa maven


【解决方案1】:

啊,你需要使用DAOFriend接口自动连线:

@Autowired
DAOFriend dao;

这是因为 Spring 使用 Java 代理机制将存储库 bean 包装到事务感知层中。使用这种方法,其他 bean 只能看到接口。

@Autowired 也有“必需的”默认行为。这意味着您的 FriendListLogic 实例不受 Spring 管理:您需要使用 @Component 注释此类(并确保它位于组件扫描路径中)或通过字符串上下文显式创建它。

【讨论】:

  • 完成但仍然无法正常工作!我将这两个选项结合起来......将自动装配更改为接口并创建指向接口 imp 的 bean,但它仍然为空......它很少见......
  • 我已经更新了答案:不清楚你如何创建FriendListLogic。它应该是加载时编织的实体吗?
  • 就是这样!我将组件添加到我的 FriendListLogic 中,现在 inyection 可以正常工作(现在呵呵)我遇到了代理的其他问题...需要将 proxy-target-class="true" 添加到我的事务管理器中,但它解决了所有其他问题我在上面列出了像“笔记”!非常感谢@dma_k
  • 请记住,如果你需要proxy-target-class="true",那么你做错了什么......
【解决方案2】:

尝试将 FriendImpl 作为 bean 添加到您的 app-context.xml 中。您需要将 `xxx.yyy.zzz.FriendImpl' 替换为完全限定的类名。

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

<context:annotation-config />
<bean  class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> 
<bean id="dataSource"  class="org.springframework.jdbc.datasource.DriverManagerDataSource">
</bean>

<bean id="entityManagerFactory"   class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="persistenceUnitName" value="persistence" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="database" value="MYSQL" />
            <property name="showSql" value="false" /> 
            <property name="generateDdl" value="false" />
            <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"  />
        </bean>
    </property>
    <property name="loadTimeWeaver">  
        <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"></bean>  
    </property>
</bean>

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

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"></bean>  

<bean id="friendDao" class="xxx.yyy.zzz.FriendImpl"/>

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

【讨论】:

  • 它工作正常!仍然有同样的问题!而且我不认为这是一个解决方案,因为如果我使用组件扫描并将它们注释为@Repositorys ...我认为我不需要直接在我的应用程序上下文中声明bean!或者至少这就是我所相信的!
猜你喜欢
  • 1970-01-01
  • 2016-08-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-28
  • 2015-03-16
  • 1970-01-01
相关资源
最近更新 更多