gpt4 book ai didi

java - 为什么父类中的@PostConstruct 方法在子类中的@PostConstruct 方法之后执行?

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:24:09 26 4
gpt4 key购买 nike

我对下面代码的结果有点困惑。
父 Controller :

@Controller
public abstract class ParentController{

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


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

子 Controller :

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

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

结果如下:
Parent-----构造函数
child -----构造函数
child -----PostConstruct
Parent-----PostConstruct

我不知道为什么 parent 的 postConstruct 在 child 的 postConstruct 之后。

最佳答案

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

发生了什么:

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

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

  3. 调用父类的构造函数

  4. 执行父类的构造函数

  5. 父类构造完成

  6. 执行子类的构造函数

  7. 子类构造完成

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

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

UPD:(为此感谢@Andreas!)

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

关于java - 为什么父类中的@PostConstruct 方法在子类中的@PostConstruct 方法之后执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36862079/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com