我尝试按照本教程创建一个自定义存储库
:https://www.baeldung.com/spring-data-jpa-method-in-all-repositories
我的应用程序构建失败并出现错误:
NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.demo.dao.ExtendedStudentRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
我的完整源代码: https://github.com/sesong11/springjpa-custom-repo
有很多类似的问题,但没有一个适合我。也许是当前版本 2.1.1 上的 Spring 问题,或者我错过了一些配置。
最佳答案
要使测试正常运行,您必须执行以下操作:
1) 将 StudentJPAH2Config
中 basePackages
的错误定义替换为 com.example.demo.dao
,或者最好将其删除为冗余:
@Configuration
@EnableJpaRepositories(repositoryBaseClass = ExtendedRepositoryImpl.class)
public class StudentJPAH2Config {
}
2) 同时将 @ComponentScan
中的 basePackages
和 DemoApplication
类中的 @EntityScan
替换为 com .example.demo.dao
和 com.example.demo.entity
。或者最好完全删除这些注释和 @EnableTransactionManagement
注释:
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
3) 添加no-argument constructor到实体学生
。
4) 更正您的测试类 - 使用 @DataJpaTest测试 DAO 层并导入您的 StudentJPAH2Config
配置:
@RunWith(SpringRunner.class)
@DataJpaTest
@Import(StudentJPAH2Config.class)
public class ExtendedStudentRepositoryIntegrationTest {
//...
}
通过这些更正,我已经成功运行了您的测试。
关于java - 创建 Spring Data JPA 的自定义存储库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53921123/