我遵循了此处发布的教程,以获取与Spring Data JPA一起使用的基础应用程序。现在,我如何理解,使用配置
<jpa:repositories base-package="my.package.to.scan" />
应该会导致Spring Data JPA对该软件包进行扫描,以获取扩展的接口JpaRepository
并为其创建一个concreate
bean,以便可以使用简单的Spring在我的服务类中的任何位置使用它@Autowired
。但是它失败了,说它找不到具有className的bean(这是创建时仅使用去大写字母的ClassName获得的默认名称)。
但是,当我像这样在我的applicationContext中手动配置bean时:
<bean id="ClassName" class="my.package.to.scan.ClassName"/>
Spring能够找到bean。然后我当然会得到一个错误,因为我想从一个接口创建一个bean,这显然是行不通的。但是关键是,似乎Spring Data
JPA“自动bean创建”似乎以某种方式失败了。
我附上了相关代码,因此您可以看一下。顺便说一句,我应该提到我正在开发一个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" />
问题很可能出在您未显示的某些配置中。如果您发布了所得到的错误,那也很好。这可能与您的想法有所不同。
我注意到您的配置的一件事是您使用context:annotation-config
而不是context:component- scan
。后者将基于@Component
注释家族自动检测并创建bean 。前者不这样做。
除此之外,您发布的所有内容看起来都应该可以运行,尽管有一些奇怪的事情,我稍后会谈到。我将所有发布的代码复制到一个示例项目中,并填写了一些细节,例如maven
pom
,persistence.xml和applicationContext.xml的缺失部分。我还向该服务添加了一个“创建”方法,因此它实际上可以执行某些操作。有了这些,并有一个主要的类来驱动这一切,这是一个可运行的示例。您可以浏览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
现在,我注意到了奇怪的地方。从顶部:
PersistenceAnnotationBeanPostProcessor
添加到applicationContext.xml
。它没有为您做任何事情。当然,可能还有其他未显示的代码需要它。@Repository
客户服务上的注释应该用于DAO类或与数据库交互的类。服务的适当注释为@Service
。@Resource
ICustomerRepository上的注释主要用于标记字段和自动装配的方法。我不确定是什么让您考虑将其放置在存储库界面上,但是它在那里什么也没做。@Transactional
。这属于您的服务,您已经准备好了,这很好。请注意,它仍可与@Transactional
存储库上的一起使用,因为它仅加入了服务启动的现有事务。@Component``@Repository
所以…如果这还没有向您解释某些事情,如果您给我一个特定的错误,我可能可以解释您为什么得到它,并告诉您如何做才能正确。
大家好,我收到下一个错误,我是使用Hibernate的新手
这是我的当前设置:ProjectRepo: ProjectService: ProjectRestController:
我在运行代码时出错。 错误消息: 类型异常报告 消息Servlet。servlet mvc调度程序的init()引发异常 说明服务器遇到内部错误,无法满足此请求。 例外情况 javax。servlet。ServletException:Servlet。servlet mvc调度程序的init()引发异常组织。阿帕奇。卡塔琳娜。验证者。AuthenticatorBase。调用(Authenticat
问题内容: 我试图将spring boot + redis集成到我的应用程序中。 pom.xml中的相关设置如下所示, 应用主要如下 applicationContext.xml的内容如下, 我的服务代码如下 然后运行程序并得到以下异常, 似乎下面的代码出错了。 redisT为null,未按预期初始化。 我应该如何解决此问题? 非常感谢。 问题答案: 我的控制器代码确实犯了一个错误。我的原始控制器
我在Spring+SpringMVC+Hibernate+MySQL web应用程序中的Spring配置有一个问题。Spring无法创建我在Service类中宣布的bean。 下面是Controller类 应用程序-上下文 最后是我的StackTrace 原因:org.SpringFramework.Beans.Factory.BeanCreationException:无法自动连接字段:priv
我试图使用-@runwith(SpringJUnit4ClassRunner.class)@ContextConfiguration({“classpath:some.xml”})运行spring JUnit测试用例 xml在内存db详细信息中定义了bean