Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why @PostConstruct method in parent class execute after @PostConstruct method in child class?

I am a little confused about the result of below code.
ParentController:

@Controller
public abstract class ParentController{

@PostConstruct
public void init(){
    System.out.println("Parent-----PostConstruct");
}


public ParentController(){
    System.out.println("Parent-----constructor");
}
} 

ChildController:

@Controller
public class ChildController extends ParentController {
 @PostConstruct
public void init() {
    System.out.println("Child-----PostConstruct");
}

public ChildController(){
    System.out.println("Child-----constructor");
}
}

the result is below:
Parent-----constructor
Child-----constructor
Child-----PostConstruct
Parent-----PostConstruct

I don't know why parent's postConstruct is after child's postContruct.

like image 873
mengying.ye Avatar asked Apr 26 '16 10:04

mengying.ye


1 Answers

This happens because you are overriding @PostConstruct method.

What is going on:

  1. Constructor of child class is called.

  2. Constructor of child class calls super

  3. Constructor of parent class is called

  4. Constructor of parent class is executed

  5. Constructor of parent class is finished

  6. Constructor of child class is executed

  7. Constructor of child class is finished

  8. @PostConstruct of child class is called, executed, and finished(because we called the constructor of child class)

  9. @PostConstruct of parent class is called, executed, and finished(because we called the constructor of parent class)

UPD: (thanks @Andreas for this!)

  1. @PostConstruct of parent class won't be called at all in this case.
    Spring will not call a parent class @PostConstruct method that is overridden by the child class @PostConstruct method, because it knows that it would just end up calling the same method twice (the child method), and Spring knows that would be wrong to do.
like image 113
Pavel Gordon Avatar answered Nov 15 '22 17:11

Pavel Gordon