当覆盖 @PostConstruct 方法时,当创建子类时,父类中的方法会被调用吗?

huangapple go评论82阅读模式
英文:

When overriding the @PostConstruct method, is the method in the parent called when a child is created?

问题

遇到了这个问题:

https://stackoverflow.com/questions/36862079/why-postconstruct-method-in-parent-class-execute-after-postconstruct-method-in

但是当我将相同的代码放入一个简单的Spring Boot应用程序中时,我得到的结果是:

父类-----构造函数
子类-----构造函数
子类-----PostConstruct

显示父类的 @PostConstruct 方法在子类实例化时未被调用。

是什么解释了这种差异?

英文:

Ran into this question:

https://stackoverflow.com/questions/36862079/why-postconstruct-method-in-parent-class-execute-after-postconstruct-method-in

But when I took the same code and put it in a simple Spring Boot app, what I get is:

Parent-----constructor
Child-----constructor
Child-----PostConstruct

showing that the parent @PostConstruct method is NOT called when a child is instantiated.

What explains the difference ?

答案1

得分: 2

UPDATED

另一个问题是错误的。

由于子级的 @PostConstruct 方法覆盖了父级的 @PostConstruct 方法,Spring 足够智能,只会调用该方法一次,而且由于子方法没有调用 super.init(),所以只会打印出子级的输出。

父类-----构造函数
子类-----构造函数
子类-----PostConstruct

如果你重命名其中一个方法,这样子级的 @PostConstruct 方法就不会覆盖父级的 @PostConstruct 方法,那么两者都会被执行。

父类-----构造函数
子类-----构造函数
父类-----PostConstruct
子类-----PostConstruct

当我运行代码时,父级的 @PostConstruct 方法首先被调用。

英文:

UPDATED

The other question is wrong.

Since the child @PostConstruct method overrides the parent @PostConstruct method, Spring is smart enough to only invoke the method once, and since the child method doesn't call super.init(), only the output from the child is printed.

Parent-----constructor
Child-----constructor
Child-----PostConstruct

If you rename one of the 2 methods, so the child @PostConstruct method doesn't override the parent @PostConstruct method, then both are executed.

Parent-----constructor
Child-----constructor
Parent-----PostConstruct
Child-----PostConstruct

When I ran the code, the parent @PostConstruct method was called first.

huangapple
  • 本文由 发表于 2020年10月19日 18:41:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/64425702.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定