问题描述
我试图了解为什么我无法自动装配类库,但我可以在相同的包中为相同的测试自动装配一个接口存储库。当我启动应用程序时,相同的存储库按预期工作。
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. The same repository works as expected when I start the application.
首先,错误:
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
我有一个非常简单的例子。测试:
I have a very simple example. The test:
@RunWith(SpringRunner.class)
@DataJpaTest
public class PersonRepositoryTest {
@Autowired
private PersonRepository personRepository; // fail...
@Autowired
private PersonCrudRepository personCrudRepository; // works!
@Test
public void findOne() {
}
}
存储库类:
@Repository
public class PersonRepository {
//code
}
存储库界面:
@Repository
public interface PersonCrudRepository extends CrudRepository<Person, Long> {
}
,我试图在配置中找到一些细节或测试导致此问题的原因。另一种可能性是 @DataJpaTest
不支持类存储库。
After a bad experience with this same error, I'm trying to find some detail in my configuration or test what is responsible for this problem. Another possibility is @DataJpaTest
not support class repositories.
推荐答案
我认为我对这个问题是正确的。找到并阅读:
I think I was right about the problem. After find a post on Github and read the Spring Documentation:
我的 PersonRepository
被认为是常规 @Component
,因为它不是Spring Data JPA存储库(接口是)。因此,它没有加载。
My PersonRepository
is considered a regular @Component
, because it is not a Spring Data JPA repository (the interface is). So, it is not loaded.
替代方法是使用 @SpringBootTest
而不是 @ DataJpaTest
。
The alternative is use @SpringBootTest
instead of @DataJpaTest
.
这篇关于使用@DataJpaTest进行Spring测试不能使用@Repository自动装配类(但是使用接口存储库工作!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!