Spring 使用@DataJpaTest 进行测试无法使用@Repository 自动装配class(但接口存储库可以工作!)

Spring test with @DataJpaTest can't autowire class with @Repository (but with interface repository works!)

我试图理解为什么我不能自动装配 class 存储库,但我可以在 相同的包 中为 [=30] 自动装配接口存储库=]同样的测试。当我启动应用程序时,相同的存储库按预期工作。

一、错误:

Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.app.person.repository.PersonRepository' 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.support.DefaultPersonbleBeanFactory.raiseNoMatchingBeanFound(DefaultPersonbleBeanFactory.java:1493)
    at org.springframework.beans.factory.support.DefaultPersonbleBeanFactory.doResolveDependency(DefaultPersonbleBeanFactory.java:1104)
    at org.springframework.beans.factory.support.DefaultPersonbleBeanFactory.resolveDependency(DefaultPersonbleBeanFactory.java:1066)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585)
    ... 28 more

我有一个非常简单的例子。测试:

@RunWith(SpringRunner.class)
@DataJpaTest
public class PersonRepositoryTest {

    @Autowired
    private PersonRepository personRepository; // fail...

    @Autowired
    private PersonCrudRepository personCrudRepository; // works!

    @Test
    public void findOne() {
    }
}

存储库class:

@Repository
public class PersonRepository {
    //code
}

存储库界面:

@Repository
public interface PersonCrudRepository extends CrudRepository<Person, Long> {
}

bad experience with this same error 之后,我试图在我的配置中找到一些细节或测试导致此问题的原因。另一种可能性是 @DataJpaTest 不支持 class 存储库。

我想我对这个问题的看法是正确的。找到 post on Github and read the Spring Documentation:

@DataJpaTest can be used if you want to test JPA applications. By default it will configure an in-memory embedded database, scan for @Entity classes and configure Spring Data JPA repositories. Regular @Component beans will not be loaded into the ApplicationContext.

我的 PersonRepository 被认为是常规 @Component,因为它不是 Spring Data JPA 存储库(接口是)。所以,它没有加载。

另一种解决方案是使用 @SpringBootTest 而不是 @DataJpaTest

此解决方案的缺点是将加载 所有 您的上下文,同时 运行 您的测试,并因此禁用测试切片。但是做这个工作。

另一个选项,仍然使用 @DataJpaTest,包括一个 @Repository 过滤器注释,如下所示:

@DataJpaTest(includeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Repository.class))

另一种选择可能是 @Import,如此处