@PostConstruct on JPA entity not called in Spring Boot
Asked Answered
O

3

5

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");
   }
}
Override answered 12/2, 2017 at 23:48 Comment(0)
O
3

I found the solution, in fact, instead of using the @PostConstruct annotation (managed by container) , I used @PostLoad (managed by ORM). Thank you.

Override answered 13/2, 2017 at 14:49 Comment(1)
You should check as correct the answer that gave you the solution. Avoid auto-answering if you already have a correct answer.Snicker
H
17

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.

Hedberg answered 13/2, 2017 at 1:1 Comment(0)
O
3

I found the solution, in fact, instead of using the @PostConstruct annotation (managed by container) , I used @PostLoad (managed by ORM). Thank you.

Override answered 13/2, 2017 at 14:49 Comment(1)
You should check as correct the answer that gave you the solution. Avoid auto-answering if you already have a correct answer.Snicker
E
0

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?

Ellary answered 13/2, 2017 at 0:50 Comment(1)
I didn't show all code in this class , but this entity has other attributes that have @Transient annotation (attributes that I won't persist ) ,and I want to add values to those attributes after the instantiation of this entity .Override

© 2022 - 2024 — McMap. All rights reserved.