首页 > 解决方案 > 为 Spring Data JPA 创建自定义存储库

问题描述

我尝试custom repository按照本教程创建一个: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 问题,或者我错过了一些配置。

标签: javaspringspring-bootspring-data-jpaspring-repositories

解决方案


要使您的测试正常工作,您必须执行以下操作:

basePackages1) 将in的不正确定义替换StudentJPAH2Configcom.example.demo.dao,或者更好地将其删除为多余的:

@Configuration
@EnableJpaRepositories(repositoryBaseClass = ExtendedRepositoryImpl.class)
public class StudentJPAH2Config {
}

2) 也将basePackagesin@ComponentScan@EntityScaninDemoApplication类替换为com.example.demo.daoand com.example.demo.entity。或者最好完全删除这些和@EnableTransactionManagement注释:

@SpringBootApplication
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}

3)向实体添加一个无参数构造函数Student

4) 更正您的测试类 - 使用@DataJpaTest测试 DAO 层并导入您的StudentJPAH2Config配置:

@RunWith(SpringRunner.class)
@DataJpaTest
@Import(StudentJPAH2Config.class)
public class ExtendedStudentRepositoryIntegrationTest {
   //...
}

通过这些更正,我已成功运行您的测试。


推荐阅读