Spring Boot多模块测试:找不到entityManagerFactory及ReservesRepository Bean求助
问题根源分析
- JPA核心依赖缺失:data模块未引入
spring-boot-starter-data-jpa,Spring无法为JpaRepository接口生成代理Bean,同时JPA核心组件entityManagerFactory也无法被自动配置。 - 测试上下文配置错误:测试类使用
@SpringBootTest(classes = ReservesServiceImpl.class)仅加载单个服务类,未启动完整Spring Boot应用上下文,导致JPA自动配置、Repository扫描等核心逻辑未生效。 - 测试依赖不全:reserve-management模块的测试依赖未包含data模块,测试时无法找到Repository类。
解决方案步骤
1. 修复data模块的pom.xml,添加JPA依赖
在data模块的<dependencies>节点中加入spring-boot-starter-data-jpa,这是Spring Data JPA的核心依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency>
2. 完善reserve-management模块的pom.xml,补充data模块依赖
在reserve-management的<dependencies>中添加data模块依赖,确保测试时能访问Repository类:
<dependency> <groupId>com.hotel</groupId> <artifactId>data</artifactId> <version>0.0.1-SNAPSHOT</version> </dependency>
3. 修改测试类的上下文配置
将@SpringBootTest指定为reserve-management模块的主应用类(例如ReserveManagementApplication,替换为你实际的主类名),同时移除冗余的@ComponentScan(主应用类的@SpringBootApplication已包含组件扫描逻辑):
修改后的测试类代码:
package com.hotel.reservemanagement.service; import static org.junit.jupiter.api.Assertions.assertEquals; import java.util.Optional; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.transaction.annotation.Transactional; import com.hotel.model.reserve.Reserve; import com.hotel.service.reserve.ReservesService; // 替换为你的reserve-management模块主应用类 @SpringBootTest(classes = ReserveManagementApplication.class) public class ReservesServiceTests { @Autowired private ReservesService reservesService; // 注入接口而非实现类,符合依赖倒置原则 @Test @Transactional void testSave () { Optional<Reserve> reserve = this.reservesService.findById(2L); reserve.get().setAdults(3L); this.reservesService.save(reserve.get()); Optional<Reserve> reserveResult = this.reservesService.findById(2L); assertEquals(3L, reserveResult.get().getAdults()); } }
补充说明
- 若主应用类的
@SpringBootApplication已覆盖com.hotel根包扫描,无需额外添加@ComponentScan,Spring会自动识别Repository、Service等Bean。 - 注入接口而非实现类是Spring开发的最佳实践,可降低代码耦合度,便于后续替换实现逻辑。
内容的提问来源于stack exchange,提问作者Xorlita
相关产品推荐
相关产品推荐

