我正在使用Spring Boot并且我将@PostConstrcut注释添加到我的JPA实体中,如图所示,但是当实体被实例化时,这个拦截器永远不会被调用。
@Entity
public class MyTableName implements java.io.Serializable {
// all attributes
@PostConstruct
public void init(){
// This code never called
System.out.println("PostConstruct");
}
}
答案 0 :(得分:3)
JPA实体不是Spring托管bean,因此Spring永远不会调用@PostConstruct
。实体有自己的实体监听器注释,但@PostConstruct
的语义没有任何内容(@PrePersiste
和@PostLoad
可能是最接近的)。实体需要具有默认构造函数,因为所有JPA实现都使用Class.newInstance()作为默认实例化策略。一个好的JPA提供程序将允许您自定义实例化策略,因此可以编写自己的@PostConstruct
拦截并调用它,如果需要,也可以@Autowire
将bean编入实体。但是,您永远不应该将JPA实体注册为Spring bean。
答案 1 :(得分:1)
您只需要确保该实体也注册为Spring托管bean,您可以在类@Component
上使用MyTableName
注释。
答案 2 :(得分:1)
答案 3 :(得分:0)
为什么要在实体bean中包含@PostConstruct?我觉得这里有一种设计气味。也许你指的是使用@PrePersist,@ PreUpdate或@PostPersist @PostUpdate注释在保存实体之前或之后运行代码的方法?