5

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?

Pavel_K
  • 10,748
  • 13
  • 73
  • 186

2 Answers2

5

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

kolossus
  • 20,559
  • 3
  • 52
  • 104
0

I believe that @PostConstruct on the parent class is not called. There can be only one @PostConstruct method. So the methods of the parent class are not inspected. You need to explicitly call it by super.doIt()