java - 创建 Spring Data JPA 的自定义存储库

标签 java spring spring-boot spring-data-jpa spring-repositories

我尝试按照本教程创建一个自定义存储库: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) 将 StudentJPAH2ConfigbasePackages 的错误定义替换为 com.example.demo.dao,或者最好将其删除为冗余:

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

2) 同时将 @ComponentScan 中的 basePackagesDemoApplication 类中的 @EntityScan 替换为 com .example.demo.daocom.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/

相关文章:

java - 嵌套集合 lambda 迭代

java - 部署 Spring MVC 应用程序时出现异常?

java - RestTemplate.postForObject - 错误 : org. springframework.web.client.HttpClientErrorException:400 错误请求

Spring Boot ServletRegistrationBean 和部署到外部 Tomcat

java - Spring Boot 中的 SLF4J 冲突

java - 递归是如何工作的?

java - 为什么我的 Thymeleaf 仅显示列表的最后一行

java - 为嵌入式 Jetty 中的多个路径添加 servlet 过滤器

java - 在 Spring WS 中捕获 EndpointNotFound

Docker 挂载发生在入口点执行之前或之后