为什么父类中的@PostConstruct方法在子类中的@PostConstruct方法之后执行? [英] Why @PostConstruct method in parent class execute after @PostConstruct method in child class?

查看:427
本文介绍了为什么父类中的@PostConstruct方法在子类中的@PostConstruct方法之后执行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对以下代码的结果感到有些困惑.
ParentController:

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:

ChildController:

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

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

结果如下:
父----构造函数
子-----构造函数
子级----- PostConstruct
父----- PostConstruct

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

我不知道为什么父母的postConstruct在孩子的postContruct之后.

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

推荐答案

发生这种情况是因为您要覆盖@PostConstruct方法.

This happens because you are overriding @PostConstruct method.

发生了什么事

  1. 子类的构造函数被调用.

  1. Constructor of child class is called.

子类调用的构造函数 super

父类的构造函数称为

父类的构造函数被执行

父类的构造函数完成

子类的构造函数被执行

子类的构造函数完成

@PostConstruct子类的调用,执行和完成(因为我们将其称为子类的构造函数)

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

@PostConstruct父类的调用,执行和完成(因为我们称为父类的构造函数)

UPD :(感谢@Andreas!)

UPD: (thanks @Andreas for this!)

    在这种情况下,父类的
  1. @PostConstruct不会被调用.
    Spring不会调用被子类@PostConstruct方法覆盖的父类@PostConstruct方法,因为它知道最终只会调用相同的方法两次(子方法),而Spring知道这样做是错误的

这篇关于为什么父类中的@PostConstruct方法在子类中的@PostConstruct方法之后执行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆