未在 Spring Boot 中调用的 JPA 实体上的 @PostConstruct

Yas*_*nou 2 java spring jpa postconstruct spring-boot

我正在使用 Spring Boot 并且我在我的 JPA 实体中添加了 @PostConstrcut 注释,如图所示,但是当实体被实例化时,这个拦截器永远不会被调用。

@Entity
public class MyTableName implements java.io.Serializable {
   // all attributes
   @PostConstruct
   public void init(){
     // This code never called
     System.out.println("PostConstruct");
   }
}
Run Code Online (Sandbox Code Playgroud)

Kla*_*aek 11

JPA 实体不是 Spring 管理的 bean,因此 Spring 永远不会调用@PostConstruct. 实体有自己的实体侦听器注释,但没有与@PostConstruct(@PrePersist并且@PostLoad可能是最接近的)的语义。实体需要有一个默认构造函数,因为所有 JPA 实现都使用 Class.newInstance() 作为默认实例化策略。一个好的 JPA 提供者将允许您自定义实例化策略,因此可以编写自己的拦截@PostConstruct并调用它,如果需要,也可以将@Autowirebean 注入实体。但是,您永远不应该将 JPA 实体注册为 Spring bean。