Order of @PostConstruct and inheritance

时光怂恿深爱的人放手 提交于 2019-12-10 20:56:15

问题


Let's suppose we have the following classes

public abstract class AbstractFoo {

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

public class Foo extends AbstractFoo {

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

When AbstractFoo.doIt() and Foo.doIt() will be called - what is the order?


回答1:


@PostConstruct is the last thing to get executed in the initialization of a given managed bean, relative to its position in the inheritance chain. From the spec

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.

Pro Tip: With CDI 2.0, you can use @Inject to declare an initializer method as an alternative @PostConstruct and the restriction that you can have only one in a given class. The difference here is that @PostConstruct is still executed last and is the only place you can be guaranteed that all injected components will be available.



来源:https://stackoverflow.com/questions/45906368/order-of-postconstruct-and-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!