Search code examples
javajakarta-eedependency-injectioncdi

Order of @PostConstruct and inheritance


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?


Solution

  • @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.