我对下面代码的结果有点困惑。
父控制器:
@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 方法。
到底是怎么回事:
-
调用子类的构造函数。
-
子类调用的构造函数super
-
调用父类的构造函数
-
执行父类的构造函数
-
父类构造函数完成
-
子类的构造函数被执行
-
子类的构造函数完成
-
子类的@PostConstruct被调用、执行、完成(因为我们调用了子类的构造函数)
-
@PostConstruct of parent class is called, executed, and finished(because we called the constructor of parent class)
UPD:(感谢@Andreas!)
- 在这种情况下,父类的 @PostConstruct 根本不会被调用。
Spring不会调用被子类@PostConstruct方法覆盖的父类@PostConstruct方法,因为它知道它最终只会调用同一个方法两次(子方法),并且Spring知道这样做是错误的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)