我按照发布here的教程来获得使用Spring Data JPA的基础应用程序。现在,我如何理解,使用配置
<jpa:repositories base-package="my.package.to.scan" />
应该导致Spring Data JPA扫描包以扩展JpaRepository
的接口并创建它的concreate bean,以便可以使用简单的Spring @Autowired
在我的服务类中的任何地方使用它。但它失败了,说它无法找到一个带有className的bean(这是bean在创建时获得的默认名称,只需使用去大写的ClassName)。
但是,当我在我的applicationContext中手动配置bean时,如下所示:
<bean id="ClassName" class="my.package.to.scan.ClassName"/>
Spring能够找到bean。我当然得到一个错误,因为我想从界面创建一个bean,这显然无法工作。但问题是,它似乎是Spring Data JPA&#34;自动创建bean&#34;似乎以某种方式失败。
我附上相关代码,以便您查看。顺便说一句,我应该提到我正在开发一个portlet,所以不要错过我为什么没有spring-config。我目前只使用applicationConfig和一个MyPortlet-Portlet.xml进行portlet配置(但这不应该与此问题相关)。我添加了import语句只是为了确保我没有使用错误的注释/类。
的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 - 只是CustomerService的接口
import model.entities.Customer;
public interface ICustomerService {
// example method
public Customer getCustomer(Long customerId);
}
CustomerService - 我的应用程序逻辑用于获取/设置ORM数据的类
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 - 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);
}
客户 - 我的样本实体
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;
}
}
我刚刚从WebSphere的classpath地狱来了(该死的,这是一个很好的产品)现在我在这里。希望有人能帮助我。
基本解释了什么是出了问题并且可能更好地理解弹簧自动注射功能将是很好的。我已经阅读了spring文档,但说实话:有很多方法可以配置一些东西,而且我不太清楚在选择其中一种配置样式时真正需要什么。
修改
尝试更新项目后,我仍然收到错误消息。按此处要求更多细节(追踪):
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)
编辑#2 根据要求添加applicationContext.xml(包括我根据正在进行的讨论所做的更改)
<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" />
答案 0 :(得分:19)
问题很可能出在您未显示的某些配置中。如果你发布了你得到的错误也会很好。它可能与您认为的不同。
我注意到您的配置有一点是您使用的是context:annotation-config
而不是context:component-scan
。后者将根据@Component
注释系列自动检测并创建bean。前者不这样做。
除此之外,你发布的所有内容看起来都应该有效,尽管有几件奇怪的东西,我马上就会谈到。我将您发布的所有代码复制到示例项目中,并填写了一些详细信息,例如maven pom,persistence.xml和the applicationContext.xml的缺失部分。我还为服务添加了“创建”方法,因此它实际上会做一些事情。有了这些和一个主要类来驱动它,它是一个可运行的例子。您可以browse the code on github,或者您可以使用以下代码克隆并运行它:
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
现在我注意到了一些奇怪的事情。从顶部:
applicationContext.xml
的{{3}}。它没有为你做任何事情。当然,可能还有其他需要它的代码,你没有展示过。@Repository
注释是PersistenceAnnotationBeanPostProcessor
,或与数据库交互的类。适当的服务注释是supposed to be used on DAO classes。@Resource
注释主要是@Service
。我不确定是什么让你想把它放在你的存储库界面上,但它没有做任何事情。@Transactional
。这属于你的服务,你已经在那里,所以没关系。请注意,它仍然可以与存储库中的@Transactional
一起使用,因为它只是加入了服务启动的现有事务。@Component
相关的注释(服务中的@Repository
),您也没有使用used for marking fields and methods for autowiring。这可能会给你带来一些问题。我没有打开组件扫描,而是在示例项目中使用XML手动创建了服务bean。所以...如果这对你没有解释,如果你给我一个特定的错误,我可以解释你为什么要得到它并告诉你如何做到正确。