gpt4 book ai didi

java - @PostConstruct 的顺序和继承

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:02:54 37 4
gpt4 key购买 nike

假设我们有以下类

public abstract class AbstractFoo {

@PostConstruct
private void doIt() {
//
}
}

public class Foo extends AbstractFoo {

@PostConstruct
private void doIt() {
//
}
}

何时调用 AbstractFoo.doIt() 和 Foo.doIt() - 顺序是什么?

最佳答案

@PostConstruct是在给定托管 bean 的初始化中执行的最后 事情,相对于它在继承链中的位置。来自规范

The container must ensure that:

  • Initializer methods (i.e. @PostConstruct) declared by a class X in the type hierarchy of the bean are called after all injected fields declared by X or by superclasses of X have been initialized.

  • Any @PostConstruct callback declared by a class X in the type hierarchy of the bean is called after all initializer methods declared by X or by superclasses of X have been called, after all injected fields declared by X or by superclasses of X have been initialized.

专业提示:对于 CDI 2.0,you can use @Inject to declare an initializer method作为替代 @PostConstruct 和在给定类中只能有一个的限制。这里的区别是 @PostConstruct 仍然最后执行,并且是唯一可以保证所有注入(inject)组件都可用的地方。

关于java - @PostConstruct 的顺序和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45906368/

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