春季数据JPA - 注射失败 - BeanCreationException:无法自动装配领域 [英] Spring Data JPA - injection fails - BeanCreationException: Could not autowire field

查看:2343
本文介绍了春季数据JPA - 注射失败 - BeanCreationException:无法自动装配领域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我也跟着教程贴这里得到一个基础的应用程序与Spring数据JPA工作。现在,我该怎么理解,使用配置

 < JPA:仓库基础包=my.package.to.scan/>

应导致该包被Spring数据JPA beeing扫描扩展接口 JpaRepository 并创建它的一个concreate豆因此它可以在任何地方我的服务类中使用简单的使用春 @Autowired 。但它失败了,说,它不能找到类名一个bean(这是默认名称时创建的,简单地使用去大写类名的豆获得)。

然而,当我manualy配置豆在我的applicationContext是这样的:

 <豆的id =类名级=my.package.to.scan.ClassName/>

春天是能够找到的bean。因为我想创建从一个接口,这显然不能工作,一个bean我那么当然得到一个错误。但问题是,它似乎像春天数据JPA自动创建豆,似乎以某种方式失败。

我附上相关code,所以你可以看看它。顺便说一句,我要指出,我正在开发一个portlet,所以不要奇怪为什么我没有弹簧的配置。我目前只使用applicationConfig加上时,MyPortlet-portlet.xml中的portlet的配置(但应不相应和对这个问题)。我添加了import语句只是为了确保我不是用错了annotions /班。

的applicationContext.xml

 <豆*** ALL MY XMLN的和XSI的*** />
<背景:注解配置/>
< JPA:仓库基础包=model.repositories/>// JPA具体的配置在这里:数据源,persistenceUnitManager exceptionTranslator,entityManagerFactory的,SessionFactory对象,transactionManager的 - 不应该是有关这个问题,告诉我,如果我错了< bean类=org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor/>

ICustomerService - 只为一个的CustomerService接口

 进口model.entities.Customer;
公共接口ICustomerService {
        //实例方法
    公共客户getCustomer(龙客户ID);
}

的CustomerService - 我的应用程序逻辑来获得使用该类/套ORM数据

 进口org.springframework.beans.factory.annotation.Autowired;
进口org.springframework.data.domain.Page;
进口org.springframework.data.domain.Pageable;
进口org.springframework.stereotype.Repository;
进口org.springframework.transaction.annotation.Transactional;
进口model.entities.Customer;
进口model.repositories.CustomerRepository;
进口model.service.interfaces.ICustomerService;
@Repository
@Transactional(只读=真)
公共类的CustomerService实现ICustomerService {
    @Autowired
    私人CustomerRepository库;    //实例方法
    @覆盖
    公共客户getCustomer(龙客户ID){
        返回repository.findById(客户ID);
    }

CustomerRepository - 为Spring JPA的数据存储库

 进口javax.annotation.Resource;
进口org.springframework.data.jpa.repository.JpaRepository;
进口org.springframework.transaction.annotation.Transactional;
进口model.entities.Customer;
@Resource
@Transactional(只读=真)
公共接口CustomerRepository扩展JpaRepository<客户,朗GT&{    公众客户findById(长ID);
}

客户 - 我的样本实体

 进口javax.persistence.Column;
进口javax.persistence.Entity;
进口javax.persistence.GeneratedValue;
进口javax.persistence.GenerationType;
进口javax.persistence.Id;
进口javax.persistence.Table;@实体
@Table(NAME =客户)
公共类客户{    @ID
    @GeneratedValue(策略= GenerationType.IDENTITY)
    @Column(NAME =ID_CUSTOMER)
    私人长期身份证;    @Column(NAME =dbfirstname)
    私有String的firstName;    @Column(NAME =DBNAME)
    私人字符串的lastName;    众长的getId(){
        返回ID;
    }    公共字符串的getFirstName(){
        返回的firstName;
    }    公共无效setFirstName(字符串的firstName){
        this.firstName =名字;
    }    公共字符串getLastName(){
        返回lastName的;
    }    公共无效setLastName(字符串的lastName){
        this.lastName = lastName的;
    }
}

我刚刚从地狱类路径来与WebSphere(该死的,什么是傅**编了产品),现在我在这里。希望有人能帮助我与此有关。

什么exacly不顺心,也许提供了一个更好地了解弹簧自动装配注入功能将是巨大的一个基本解释。我读过的春天的文档,但说实话:有这么多的方式来配置的东西,这不是对我非常明显选择的配置方式之一,当真正需要的。

修改

试图更新项目后我仍然得到错误。这里要求多一点细节(跟踪):

 异常创建:org.springframework.beans.factory.BeanCreationException:错误创建名为'的CustomerService'豆:自动装配依赖注射失败;嵌套的例外是org.springframework.beans.factory.BeanCreationException:无法自动装配领域:私人model.repositories.CustomerRepository model.service.CustomerService.repository;嵌套的例外是org.springframework.beans.factory.BeanCreationException:错误创建一个名为豆'customerRepository':FactoryBean的扔在创建对象除外;嵌套的例外是显示java.lang.NullPointerException
    在org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
    在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
    [...]
        在com.ibm.ws.http.HttpConnection.run(HttpConnection.java:522)
    在com.ibm.ws.util.ThreadPool $ Worker.run(ThreadPool.java:1563)
org.springframework.beans.factory.BeanCreationException:引起无法自动装配领域:私人model.repositories.CustomerRepository model.service.CustomerService.repository;嵌套的例外是org.springframework.beans.factory.BeanCreationException:错误创建一个名为豆'customerRepository':FactoryBean的扔在创建对象除外;嵌套的例外是显示java.lang.NullPointerException
    在org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)
    在org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    在org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
    ... 96更多
org.springframework.beans.factory.BeanCreationException:引起错误创建名为'customerRepository'豆:FactoryBean的扔在创建对象除外;嵌套的例外是显示java.lang.NullPointerException
    在org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:149)
    在org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:102)
    在org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1442)
    在org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:248)
    在org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    在org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:848)
    在org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:790)
    在org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
    在org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
    ... 98更多
显示java.lang.NullPointerException:产生的原因
    在org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.getStatus(JtaStatusHelper.java:73)
    在org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.isActive(JtaStatusHelper.java:115)
    在org.hibernate.engine.transaction.internal.jta.CMTTransaction.join(CMTTransaction.java:149)
    在org.hibernate.ejb.AbstractEntityManagerImpl.joinTransaction(AbstractEntityManagerImpl.java:1215)
    在org.hibernate.ejb.AbstractEntityManagerImpl.postInit(AbstractEntityManagerImpl.java:177)
    在org.hibernate.ejb.EntityManagerImpl<&初始化GT;(EntityManagerImpl.java:89)
    在org.hibernate.ejb.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:179)
    在org.hibernate.ejb.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:174)
    在sun.reflect.NativeMethodAccessorImpl.invoke0(本机方法)
    在sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:48)
    在sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    在java.lang.reflect.Method.invoke(Method.java:600)
    在org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.invokeProxyMethod(AbstractEntityManagerFactoryBean.java:376)
    在org.springframework.orm.jpa.AbstractEntityManagerFactoryBean$ManagedEntityManagerFactoryInvocationHandler.invoke(AbstractEntityManagerFactoryBean.java:517)
    在$ Proxy325.createEntityManager(来源不明)    在org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:234)
    在$ Proxy328.createNamedQuery(来源不明)
    在org.springframework.data.jpa.repository.query.NamedQuery<&初始化GT;(NamedQuery.java:74)
    在org.springframework.data.jpa.repository.query.NamedQuery.lookupFrom(NamedQuery.java:96)
    在org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$DeclaredQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:128)
    在org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:162)
    在org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:71)
    在org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:303)
    在org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:157)
    在org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:120)
    在org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:39)
    在org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:142)

编辑#2
compleate的applicationContext.xml(包括,我做的基础上进行的讨论的变化)增加的要求

 &LT;背景:注解配置/&GT;&LT; JPA:仓库基础包=model.repositories/&GT;&LT;背景:组件扫描基包=模式,model.repositories,model.service,控制器/&GT;&LT; bean类=model.service.CustomerService/&GT;
&LT; bean类=model.service.OrderService/&GT;
&LT; bean类=model.repositories.CustomerRepository/&GT;
&LT; bean类=model.repositories.OrderRepository/&GT;
&LT;豆的id =myExceptionTranslator级=org.springframework.orm.hibernate4.HibernateExceptionTranslator/&GT;&LT; JEE:JNDI的查找ID =数据源JNDI名称=的jdbc / MYDATA
    资源引用=真正的缓存=真/&GT;
&LT;豆的id =PUM
    类=org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager&GT;
    &LT;属性名=persistenceXmlLocations&GT;
        &LT;列表&gt;
            &LT; VALUE&GT;的classpath *:META-INF / OverridePersistence.xml&LT; /值&GT;
        &LT; /列表&gt;
    &LT; /性&gt;
    &LT;属性名=defaultDataSourceREF =数据源/&GT;
&LT; /豆&GT;
&LT;豆ID =的entityManagerFactory
    类=org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean&GT;
    &LT;属性名=数据源REF =数据源/&GT;
    &LT;属性名=jpaVendorAdapter&GT;
        &LT; bean类=org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter&GT;
            &LT;属性名=generateDdlVALUE =真/&GT;
            &LT;属性名=数据库VALUE =MYSQL/&GT;
        &LT; /豆&GT;
    &LT; /性&gt;
    &LT;属性名=persistenceUnitManagerREF =PUM/&GT;
    &LT;属性名=persistenceUnitName来VALUE =默认/&GT;
&LT; /豆&GT;&LT;豆的id =mySessionFactory这个
    类=org.springframework.orm.hibernate4.LocalSessionFactoryBean&GT;
    &LT;属性名=数据源REF =数据源/&GT;
    &LT;属性名=packagesToScanVALUE =模式/&GT;
    &LT;属性名=hibernateProperties&GT;
        &LT; VALUE&GT; hibernate.dialect = org.hibernate.dialect.MySQLDialect&LT; /值&GT;
    &LT; /性&gt;
&LT; /豆&GT;&LT;豆的id =transactionManager的
    类=org.springframework.orm.hibernate4.HibernateTransactionManager&GT;
    &LT;属性名=entityManagerFactory的REF =entityManagerFactory的/&GT;
    &LT;属性名=SessionFactory的REF =mySessionFactory这个/&GT;
&LT; /豆&GT;&LT; TX:注解驱动/&GT;&LT; bean类=org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor/&GT;


解决方案

的问题是在一些你没有所示的结构很有可能。这也将是很好的,如果你发布你得到错误。这可能是一件比你认为它是不同的。

有一件事我注意到你的配置是您使用背景:注解配置而不是背景:组件扫描。后者将自动检测和创建基于 @Component 家庭注解豆。前者并没有做到这一点。

除此之外,您发布的一切看起来像它应该工作,但也有一些奇怪的事情,我会来一会儿。我复制你所有贴code到示例项目,填补了一些细节,像<一个href=\"https://github.com/zzantozz/testbed/blob/master/stackoverflow/10539417-basic-spring-data-jpa/pom.xml\">maven POM ,一<一href=\"https://github.com/zzantozz/testbed/blob/master/stackoverflow/10539417-basic-spring-data-jpa/src/main/resources/META-INF/persistence.xml\">persistence.xml,和失踪者<一件href=\"https://github.com/zzantozz/testbed/blob/master/stackoverflow/10539417-basic-spring-data-jpa/src/main/resources/applicationContext.xml\">the applicationContext.xml中。我还添加了创造的方法来服务,以便它实际上做一些事情。与那些在地方,驾驶它的所有主类,它是一个可运行的例子。可以browse在github 中的code,也可以克隆,并运行它:

 混帐混帐克隆://github.com/zzantozz/testbed TMP
CD TMP /计算器/ 10539417-基本簧数据JPA
MVN -q编译EXEC:JAVA -Dexec.mainClass = rds.testbed.springDataJpa.SpringDataJp

现在的我注意到了怪事。从顶部:


  • 随着给出了code,没有必要为<一个href=\"http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/orm/jpa/support/PersistenceAnnotationBeanPostProcessor.html\"><$c$c>PersistenceAnnotationBeanPostProcessor你已经添加到的applicationContext.xml 。它不为你做任何事情。当然,也有可能是其他code需要它,你没有显示。

  • 在您的CustomerService的 @Repository 注释是<一个href=\"http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/stereotype/Repository.html\">supposed要在,或类与数据库交互DAO类使用。为服务相应的注释是<一个href=\"http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/stereotype/Service.html\"><$c$c>@Service.

  • 在您的ICustomerRepository的 @Resource 标注主要是<一个href=\"http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-resource-annotation\">used对于这标志着自动装配字段和方法。我不知道是什么让你觉得把你的资料库界面,但它没有做任何事情在那里。

  • 您的存储库不应该是 @Transactional 。属于你的服务,你已经得到它那里,所以这很好。请注意,它仍然与 @Transactional 适用于存储库,因为它只是加入了服务启动现有的事务。

  • 值得注意再次证明你不使用<一个href=\"http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-scanning-autodetection\">component扫描,即使你有一个 @Component - 相关注释(即 @Repository 您服务) 。这可能是造成你的一些问题。相反,打开组件扫描的,我手动示例项目使用XML创建的服务豆。

所以...如果这没有解释的东西给你,如果你给我一个特定的错误,我也许可以解释为什么你得到它,并告诉你怎样做才能作出正确选择。

i followed the tutorial posted here to get a basis application to work with Spring Data JPA. Now, how i understood, using the configuration

<jpa:repositories base-package="my.package.to.scan" />

should result in that package beeing scanned by Spring Data JPA for interfaces extending JpaRepository and create a concreate bean of it so it can be used anywhere in my service classes using simple Spring @Autowired. But it fails, saying it can't find a bean with className (which is the default name the bean gets when created, simply using the de-capitalized ClassName).

However, when i configure the bean manualy in my applicationContext like this:

<bean id="ClassName" class="my.package.to.scan.ClassName"/>

Spring is able to find the bean. I then of course get an error because i want to create a bean from an interface, which obviously can't work. BUT the point is that it seems like the Spring Data JPA "automatic bean creation" seems to fail somehow.

I attached the relevant code so you can look at it. Btw, i should mention that i'm developing a portlet, so don't wonder why i dont have a spring-config. I'm currently using a applicationConfig only plus an MyPortlet-Portlet.xml for portlet configurations (but that should be not relevent for this problem). I added the import statements just to make sure i'm not using the wrong annotions / classes.

applicationContext.xml

<beans *** ALL MY XMLN's and XSI's *** />
<context:annotation-config />
<jpa:repositories base-package="model.repositories" />

// JPA specific configuration here: dataSource, persistenceUnitManager exceptionTranslator, entityManagerFactory, SessionFactory, transactionManager - should not be relevant for this problem, tell me if i'm wrong

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

ICustomerService - just a interface for the CustomerService

import model.entities.Customer;
public interface ICustomerService {
        // example method
    public Customer getCustomer(Long customerId);   
}

CustomerService - the class used by my application logic to get / set ORM data

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import model.entities.Customer;
import model.repositories.CustomerRepository;
import model.service.interfaces.ICustomerService;
@Repository
@Transactional(readOnly = true)
public class CustomerService implements ICustomerService{
    @Autowired
    private CustomerRepository repository;

    // example method
    @Override
    public Customer getCustomer(Long customerId){
        return repository.findById(customerId);
    }

CustomerRepository - the repository for Spring Data JPA

import javax.annotation.Resource;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
import model.entities.Customer;
@Resource
@Transactional(readOnly = true)
public interface CustomerRepository extends JpaRepository<Customer, Long>{

    public Customer findById(Long id);
}

Customer - my sample entity

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "Customers")
public class Customer{

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "ID_CUSTOMER")
    private Long    id;

    @Column(name = "dbfirstname")
    private String  firstName;

    @Column(name = "dbname")
    private String  lastName;

    public Long getId(){
        return id;
    }

    public String getFirstName(){
        return firstName;
    }

    public void setFirstName(String firstName){
        this.firstName = firstName;
    }

    public String getLastName(){
        return lastName;
    }

    public void setLastName(String lastName){
        this.lastName = lastName;
    }
}

i just came from classpath hell with WebSphere (damn, what a fu**ed up product) and now i'm here. hope somebody can help me with this.

A basic explanation of what exacly goes wrong and maybe providing a better understanding of springs autowired injection feature would be great. I've read the spring documentation, but to say the truth: there are so many ways to configure something and it's not quite visible to me WHAT is really needed when choosing one of the config styles.

EDIT

After trying to update the project i'm still getting the error. as requested here a little more details (trace):

Exception created : org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private model.repositories.CustomerRepository model.service.CustomerService.repository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerRepository': FactoryBean threw exception on object creation; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:287)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1106)
    [...]
        at com.ibm.ws.http.HttpConnection.run(HttpConnection.java:522)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1563)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private model.repositories.CustomerRepository model.service.CustomerService.repository; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerRepository': FactoryBean threw exception on object creation; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:506)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:284)
    ... 96 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerRepository': FactoryBean threw exception on object creation; nested exception is java.lang.NullPointerException
    at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:149)
    at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:102)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1442)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:248)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.findAutowireCandidates(DefaultListableBeanFactory.java:848)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:790)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:707)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:478)
    ... 98 more
Caused by: java.lang.NullPointerException
    at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.getStatus(JtaStatusHelper.java:73)
    at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.isActive(JtaStatusHelper.java:115)
    at org.hibernate.engine.transaction.internal.jta.CMTTransaction.join(CMTTransaction.java:149)
    at org.hibernate.ejb.AbstractEntityManagerImpl.joinTransaction(AbstractEntityManagerImpl.java:1215)
    at org.hibernate.ejb.AbstractEntityManagerImpl.postInit(AbstractEntityManagerImpl.java:177)
    at org.hibernate.ejb.EntityManagerImpl.<init>(EntityManagerImpl.java:89)
    at org.hibernate.ejb.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:179)
    at org.hibernate.ejb.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:174)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:48)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:600)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.invokeProxyMethod(AbstractEntityManagerFactoryBean.java:376)
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean$ManagedEntityManagerFactoryInvocationHandler.invoke(AbstractEntityManagerFactoryBean.java:517)
    at $Proxy325.createEntityManager(Unknown Source)

    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:234)
    at $Proxy328.createNamedQuery(Unknown Source)
    at org.springframework.data.jpa.repository.query.NamedQuery.<init>(NamedQuery.java:74)
    at org.springframework.data.jpa.repository.query.NamedQuery.lookupFrom(NamedQuery.java:96)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$DeclaredQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:128)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$CreateIfNotFoundQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:162)
    at org.springframework.data.jpa.repository.query.JpaQueryLookupStrategy$AbstractQueryLookupStrategy.resolveQuery(JpaQueryLookupStrategy.java:71)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.<init>(RepositoryFactorySupport.java:303)
    at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:157)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:120)
    at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:39)
    at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:142)

EDIT #2 compleate applicationContext.xml (includeing the changes i made based on the ongoing discussion) added as requested

<context:annotation-config />

<jpa:repositories base-package="model.repositories" />

<context:component-scan base-package="model,model.repositories,model.service,controller" />

<bean class="model.service.CustomerService"/>
<bean class="model.service.OrderService"/>
<bean class="model.repositories.CustomerRepository"/>
<bean class="model.repositories.OrderRepository"/>


<bean id="myExceptionTranslator" class="org.springframework.orm.hibernate4.HibernateExceptionTranslator" /> 

<jee:jndi-lookup id="dataSource" jndi-name="jdbc/mydata"
    resource-ref="true" cache="true" />


<bean id="pum"
    class="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager">
    <property name="persistenceXmlLocations">
        <list>
            <value>classpath*:META-INF/OverridePersistence.xml</value>
        </list>
    </property>
    <property name="defaultDataSource" ref="dataSource" />
</bean>


<bean id="entityManagerFactory"
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="generateDdl" value="true" />
            <property name="database" value="MYSQL" />
        </bean>
    </property>
    <property name="persistenceUnitManager" ref="pum" />
    <property name="persistenceUnitName" value="default" />
</bean>

<bean id="mySessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="packagesToScan" value="model"/>
    <property name="hibernateProperties">
        <value>hibernate.dialect=org.hibernate.dialect.MySQLDialect</value>
    </property>
</bean>

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

<tx:annotation-driven />

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

解决方案

The problem is very probably in some of the configuration you haven't shown. It would also be good if you posted the error you're getting. It might be something different than what you think it is.

One thing I notice about your config is that you're using context:annotation-config instead of context:component-scan. The latter will auto-detect and create beans based on the @Component family of annotations. The former doesn't do that.

Other than that, everything you posted looks like it should work, though there are several odd things, which I'll come to in a moment. I copied all your posted code into a sample project and filled in a few details, like a maven pom, a persistence.xml, and the missing pieces of the applicationContext.xml. I also added a "create" method to the service so it would actually do something. With those in place and a main class to drive it all, it's a runnable example. You can browse the code on github, or you can clone and run it with:

git clone git://github.com/zzantozz/testbed tmp
cd tmp/stackoverflow/10539417-basic-spring-data-jpa
mvn -q compile exec:java -Dexec.mainClass=rds.testbed.springDataJpa.SpringDataJp

Now for the oddities that I noticed. From the top:

  • With the code as given, there's no need for the PersistenceAnnotationBeanPostProcessor that you've added to the applicationContext.xml. It's not doing anything for you. Of course, there may well be other code that needs it that you haven't shown.
  • The @Repository annotation on your CustomerService is supposed to be used on DAO classes, or classes that interact with a database. The appropriate annotation for a service is @Service.
  • The @Resource annotation on your ICustomerRepository is mostly used for marking fields and methods for autowiring. I'm not sure what made you think to put it on your repository interface, but it's not doing anything there.
  • Your repository shouldn't be @Transactional. That belongs at your service, and you've already got it there, so that's fine. Note that it still works with the @Transactional on the repository because it just joins the existing transaction started by the service.
  • It's worth noting again that you're not using component scanning, even though you have a @Component-related annotation (the @Repository on your service). That might be causing you some problems. Instead of turning on component scanning, I manually created the service bean using XML in the sample project.

So... if this hasn't explained something to you, if you give me a specific error, I can probably explain why you're getting it and tell you what to do to make it right.

这篇关于春季数据JPA - 注射失败 - BeanCreationException:无法自动装配领域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆