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

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

问题描述

我对下面代码的结果有点困惑.
父控制器:

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");
}
} 

子控制器:

@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 在孩子的 postConstruct 之后.

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天全站免登陆