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

后端 未结 2 1369
野趣味
野趣味 2020-12-06 10:45

I\'m trying to understand why I can\'t autowire a class repository but I can autowire a interface repository in the same package for the same test

相关标签:
2条回答
  • 2020-12-06 11:13

    Just another alternative might be @Import as shown here https://stackoverflow.com/a/41084739/384674.

    0 讨论(0)
  • 2020-12-06 11:14

    I think I was right about the problem. After find a 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.

    My PersonRepository is considered a regular @Component, because it is not a Spring Data JPA repository (the interface is). So, it is not loaded.

    The alternative solution is to use @SpringBootTest instead of @DataJpaTest.

    The disadvantage with this solution is that will load all your context while running your test and, with this, disabling the test slicing. But do the job.

    Another option still using @DataJpaTest is include a @Repository filter annotation, like this:

    @DataJpaTest(includeFilters = @ComponentScan.Filter(type = FilterType.ANNOTATION, classes = Repository.class))
    
    0 讨论(0)
提交回复
热议问题