如何在Spring Boot JPA Entity Listener中注入Repository依赖
问题根因
你遇到的注入失败问题由多个配置疏漏共同导致:
@SpringBootApplication默认仅扫描启动类所在包my.project.package.starter及其子包下的Bean,你的MyEntityListener存放在my.project.package.spi.jpa.model路径下,不在默认扫描范围,没有被Spring容器接管。- 自定义
DomainConfiguration的@ComponentScan仅显式包含@DomainService注解的类,@Component注解的Listener未被纳入扫描规则。 - JPA默认由Hibernate自行实例化EntityListener,不会自动注入Spring管理的Bean,没有配置Spring容器与Hibernate的实例关联。
@PrePersist修饰的回调方法使用了private修饰符,不符合JPA规范,会导致方法不被触发。
修复步骤
1. 修正回调方法修饰符
将MyEntityListener中的beforeSave方法改为public:
@PrePersist public void beforeSave(MyEntity myEntity) { String serialNumber = String.format("%012d", myEntityRepository.getNextSerialNumber()); myEntity.setSerialNumber(serialNumber); }
2. 配置Hibernate关联Spring容器
在application.yml/application.properties中添加以下配置,让Hibernate从Spring容器中获取Listener实例:
spring: jpa: properties: hibernate: resource: bean_container: org.springframework.orm.jpa.SpringBeanContainer
Spring Boot 2.0+版本默认已开启该配置,低版本需手动添加。
3. 调整组件扫描规则
两种方案二选一即可:
- 方案一:在启动类上显式指定全局扫描包
@SpringBootApplication @ComponentScan(basePackages = "my.project.package") @EntityScan(basePackages = { "my.project.package.spi.jpa.model" }) @EnableJpaRepositories(basePackages = { "my.project.package.spi.jpa.repository" }) public class MyApplication { // 原有代码保持不变 } - 方案二:给
MyEntityListener添加@DomainService注解,匹配现有扫描规则@Component @DomainService public class MyEntityListener { // 原有代码保持不变 }
4. 兼容兜底方案
如果以上配置完成后仍存在注入问题,可在Listener中手动触发依赖注入:
@Component public class MyEntityListener { @Autowired private MyEntityRepository myEntityRepository; public MyEntityListener() { SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this); } // 原有@PrePersist方法 }
内容的提问来源于stack exchange,提问作者Paul-Etienne
相关产品推荐
相关产品推荐

