3

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");
   }
}
Yassine Abainou
  • 145
  • 2
  • 13

3 Answers3

14

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.

Ilya Serbis
  • 21,149
  • 6
  • 87
  • 74
Klaus Groenbaek
  • 4,820
  • 2
  • 15
  • 30
3

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

Yassine Abainou
  • 145
  • 2
  • 13
  • 4
    You should check as correct the answer that gave you the solution. Avoid auto-answering if you already have a correct answer. – SJuan76 Dec 17 '20 at 09:15
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?

anand1st
  • 1,086
  • 10
  • 16
  • 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 . – Yassine Abainou Feb 13 '17 at 14:35