【问题标题】:Why @PostConstruct method in parent class execute after @PostConstruct method in child class?为什么父类中的@PostConstruct 方法在子类中的@PostConstruct 方法之后执行?
【发布时间】:2016-08-20 02:43:31
【问题描述】:

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

@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

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

【问题讨论】:

  • 这是因为您覆盖了@PostConstruct 方法。如果你没有覆盖超类 @PostConstruct 将首先被调用。
  • @mengying.ye 看看这个。 stackoverflow.com/questions/13167058/…
  • 非常感谢,很有帮助。

标签: java spring annotations


【解决方案1】:

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

发生了什么:

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

  2. 子类的构造函数调用super

  3. 父类的构造函数被调用

  4. 父类的构造函数被执行

  5. 父类构造完成

  6. 子类的构造函数被执行

  7. 子类的构造完成

  8. 子类的@PostConstruct被调用、执行、完成(因为我们调用了子类的构造函数)

  9. 父类的@PostConstruct被调用、执行、完成(因为我们调用了父类的构造函数)

UPD:(感谢@Andreas!)

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

【讨论】:

  • 您基本上重新输入了 OP 已经知道的内容。他在问为什么会这样,而不是重申他已经知道了。
  • 这个答案很有帮助,因为这些词“因为我们调用了子类的构造函数”。用“PostConstruct”这个词的意思来读它——它的意思是“在构造之后”。
  • @ThermalEagle 好吧,它不能是“构造之前”,因为没有对象实例可以调用该方法,也不能是“构造期间”,因为它是 Spring进行调用,并且 Spring 在构造函数返回之前不会获取对象实例,因此它只能是“构造后”。
  • 第 9 步是错误的,因为 Spring 不会调用被子类 @PostConstruct 方法覆盖的父类 @PostConstruct 方法,因为它知道它最终会调用相同的方法两次(子方法),Spring 知道这样做是错误的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-25
相关资源
最近更新 更多