使用@DataJpaTest的弹簧测试不能使用@Repository自动连接类(但使用接口存储库可以工作!
2022-09-01 21:49:25
我试图理解为什么我不能自动连接类存储库,但我可以在同一包中自动连接接口存储库以进行相同的测试。当我启动应用程序时,同一存储库按预期工作。
一、错误:
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() {
}
}
存储库类:
@Repository
public class PersonRepository {
//code
}
存储库接口:
@Repository
public interface PersonCrudRepository extends CrudRepository<Person, Long> {
}
在遇到相同错误的糟糕经历之后,我试图在我的配置中找到一些细节或测试导致此问题的原因。另一种可能性是 不支持类存储库。@DataJpaTest