简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM