Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deriving from a class that has Annotation @PostConstruct

If you have a parent class which uses the @PostConstruct annotation and you create a child class that derives from it. Will the @PostConstruct method be called automatically each time an instance of the child class is created? since that @PostConstruct method is called each time an instance of the the parent is created.

I Know that in the child class it calls super(); for us automatically without us having to call it.

im just not sure if the @PostConstruct annotation is automatically called if that child class calls the super(); constructor.

like image 313
Marquis Blount Avatar asked Oct 31 '12 20:10

Marquis Blount


People also ask

What is the use of @PostConstruct annotation?

Annotation Type PostConstruct The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method MUST be invoked before the class is put into service. This annotation MUST be supported on all classes that support dependency injection.

What is @PostConstruct annotation in spring?

When we annotate a method in Spring Bean with @PostConstruct annotation, it gets executed after the spring bean is initialized. We can have only one method annotated with @PostConstruct annotation. This annotation is part of Common Annotations API and it's part of JDK module javax.

When @PostConstruct is called in Java?

Methods marked with the @PostConstruct will be invoked after the bean has been created, dependencies have been injected, all managed properties are set, and before the bean is actually set into scope.

How many times a @PostConstruct method is called?

2. @PostConstruct. Spring calls the methods annotated with @PostConstruct only once, just after the initialization of bean properties.


1 Answers

After testing this scenario, the @PostConstruct method in the base class WILL automatically be called.

The flow goes like this:

  1. When the child class is created, you are in the constructor of the child class, you then are forced into the parent class automatically.
  2. Once the parent class constructor is done you are sent back to the child class' constructor.
  3. Once the child class constructor is done you are automatically sent to the PARENT classes @PostConstruct method
like image 52
Marquis Blount Avatar answered Oct 10 '22 20:10

Marquis Blount