0

我的组件定义如下

@Component("myBo")
public class MyBO {

    @Autowired
    JpaRepository<MyData, Long> repository;

弹簧数据接口:

public interface MyDataRepository extends JpaRepository<MyData, Long> {

实体管理器定义:

    @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;

谢谢

4

1 回答 1

1

您不应该JpaRepository<MyData, Long>按原样自动装配。您应该扩展它并创建自己的接口,如下所示。

public interface MyRepository extends JpaRepository<MyData, Long> {
}

您将无法直接自动装配 JpaRepository 的原因是因为它带有NoRepositoryBean注释,并且会阻止创建它的实例。始终建议扩展基础 repo 类并创建自己的接口。

PS:不要忘记在您要创建的这些 repo 接口上启用 Jpa Repositories。否则,您将无法自动连接它们。

在您的 xml 配置中与此类似。

<jpa:repositories base-package="com.acme.repositories"/>
于 2017-07-13T10:06:25.653 回答