@PostConstruct 的顺序和继承

Order of @PostConstruct and inheritance

假设我们有以下 类

public abstract class AbstractFoo {

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

public class Foo extends AbstractFoo {

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

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

@PostConstructlast 在给定托管 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 以及在给定的 [=29] 中只能有一个的限制=].这里的区别在于 @PostConstruct 仍然是 最后执行的,并且是唯一可以保证所有注入的组件都可用的地方。

我认为父 class 上的 @PostConstruct 没有被调用。只能有一个 @PostConstruct 方法。所以父 class 的方法没有被检查。您需要通过 super.doIt()

显式调用它