Kotlin+SpringBoot中DataJpaTest报错:testEntityManager Bean创建失败
核心原因
你手动引入了spring-data-jpa和hibernate-core依赖,没有使用Spring Boot官方提供的spring-boot-starter-data-jpa starter,这直接破坏了Spring Boot的JPA自动配置链,导致容器无法自动创建EntityManagerFactory Bean。
解决方案
1. 替换JPA相关依赖
移除手动添加的spring-data-jpa和hibernate-core,改用Spring Boot的JPA starter,它会自动管理所有兼容版本的JPA/Hibernate依赖,并触发必要的自动配置:
修改后的build.gradle.kts依赖配置:
dependencies { implementation("org.springframework.boot:spring-boot-starter-data-rest") // 替换为Spring Boot官方JPA Starter implementation("org.springframework.boot:spring-boot-starter-data-jpa") implementation("org.jetbrains.kotlin:kotlin-reflect") runtimeOnly("com.h2database:h2") runtimeOnly("org.postgresql:postgresql") testImplementation("org.springframework.boot:spring-boot-starter-test") testImplementation("org.jetbrains.kotlin:kotlin-test-junit5") testRuntimeOnly("org.junit.platform:junit-platform-launcher") }
2. 验证包结构
确保你的测试类HouseRepositoryTest和带@SpringBootApplication注解的主应用类处于同一根包下,或者在主应用类上通过scanBasePackages指定扫描路径,否则Spring无法扫描到你的Repository和实体类。
3. 可选:配置测试用H2数据库
虽然@DataJpaTest会自动配置H2内存数据库,但如果需要自定义配置,可以在src/test/resources/application.properties中添加:
spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password= spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
原理说明
Spring Boot的starter封装了依赖版本管理和自动配置逻辑,spring-boot-starter-data-jpa会自动引入spring-data-jpa、hibernate-core等依赖,并触发HibernateJpaAutoConfiguration等配置类,这些类负责创建EntityManagerFactory、EntityManager等JPA核心Bean。手动引入单独依赖会跳过这些自动配置,导致容器缺少必要的Bean,从而抛出找不到EntityManagerFactory的异常。
内容的提问来源于stack exchange,提问作者IndigoParadise

