我的组件定义如下
@Component("myBo")
public class MyBO {
@Autowired
JpaRepository<MyData, Long> repository;
Spring数据接口:
public interface MyDataRepository extends JpaRepository<MyData, Long> {
Entitymanager定义:
@Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory( EntityManagerFactoryBuilder builder, @Qualifier("dmDs") final DataSource dmDs) {
LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = builder.dataSource(dmDs).packages(new String[]{"my.packages"}).build();
return localContainerEntityManagerFactoryBean;
}
我的测试因此错误而失败
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'myBO': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.jpa.repository.JpaRepository<MyData, java.lang.Long>' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.data.jpa.repository.JpaRepository<MyData, java.lang.Long>' available: expected at least 1 bean which qualifies as autowire candidate.
而以下工作正常。需要帮助来理解这种行为。
@Component
public class MyBO {
@Autowired
JpaRepository<MyData, Long> repository;
谢谢
答案 0 :(得分:1)
您不应该按原样自动装配JpaRepository<MyData, Long>
。您应该扩展它并创建自己的界面,如下所示。
public interface MyRepository extends JpaRepository<MyData, Long> {
}
您无法直接自动装配JpaRepository的原因是因为它使用NoRepositoryBean
注释进行了注释,并且无法创建它的实例。始终建议扩展基本repo类并创建自己的接口。
P.S:不要忘记在要创建的这些repo接口上启用Jpa存储库。否则你将无法自动装配它们。
与xml配置中的相似。
<jpa:repositories base-package="com.acme.repositories"/>