Reputation: 185
I'm using Spring Boot and I added @PostConstrcut annotation to my JPA Entity as shown , but When the entity is instantiated this interceptor is never called .
@Entity
public class MyTableName implements java.io.Serializable {
// all attributes
@PostConstruct
public void init(){
// This code never called
System.out.println("PostConstruct");
}
}
Upvotes: 5
Views: 7508
Reputation: 5035
JPA Entities are not spring managed beans, so Spring will never call @PostConstruct
. Entities have their own Entity listener annotations, but there is nothing with the semantics of @PostConstruct
(@PrePersist
and @PostLoad
are probably the closest). Entities need to have a default constructor, because all JPA implementations use Class.newInstance() as the default instantiation policy. A good JPA provider will allow you to customize the instantiation policy, so it is possible to write you own interception of @PostConstruct
and invoke it, it is also possible to @Autowire
spring beans into entities if you want. However you should never register JPA entities as Spring beans.
Upvotes: 17
Reputation: 185
I found the solution, in fact, instead of using the @PostConstruct annotation (managed by container) , I used @PostLoad (managed by ORM). Thank you.
Upvotes: 3
Reputation: 1176
Why would you want to have a @PostConstruct inside an entity bean? I think there's a design smell here. Maybe you are referring to methods with @PrePersist, @PreUpdate or @PostPersist @PostUpdate annotations that run code before or after saving entity?
Upvotes: 0