JSF - what is the difference between @PostConstruct and direct method call from constructor?
Asked Answered
R

1

16

In my view scoped managedBean, i need to populate a list with data from DB. Im doing this through a direct call from the constructor, something like this:

public MyClass(){
   list=populateFromDb();
}

but this method can be called in a @PostConstruct annotated method, like:

public MyClass(){
}

@PostConstruct
populateFromDb(){...}

what is the difference between this?

Reikoreilly answered 14/5, 2013 at 11:28 Comment(1)
Why use @PostConstruct?Skied
B
36

If the bean has request scope, @PostConstruct will get executed every time. It will be called after the managed bean is instantiated, but before the bean is placed in scope. Such a method take no arguments, return void, and may not declare a checked exception to be thrown. Method may be public, protected, private, or package private. If the method throws an unchecked exception, the JSF implementation must not put the managed bean into service and no further menthods on that managed bean instance will be called.

public TrainingClassForm() {

    }
  @PostConstruct
   public void init() {
       if (this.trainingListModel.getListDataModel() != null) {
          this.trainingListModel.getAllTrainingClasses();
       }

    }


Reffering you to this question of stack
In a managed bean, @PostConstruct is called after the regular Java object constructor.
when the constructor is called, the bean is not yet initialized - i.e. no dependencies are injected. In the @PostConstruct method the bean is fully initialized and you can use the dependencies

@PostConstruct is the contract that guarantees that this method will be invoked only once in the bean lifecycle . It may happen (though unlikely) that a bean is instantiated multiple times by the container in its internal working, but it guarantees that @PostConstruct will be invoked only once.
If your class performs all of its initialization in the constructor, then @PostConstruct is indeed redundant.
However, if your class has its dependencies injected using setter methods, then the class's constructor cannot fully initialize the object, and sometimes some initialization needs to be performed after all the setter methods have been called, hence the use case of @PostConstruct
Also see this and this

Barnaul answered 14/5, 2013 at 11:34 Comment(1)
plus one from my side. If i wish to initialise an inputtext field with a value fetched from database, I am able to do it with the help of PostConstruct, but fails when try to do the same inside the constructor. I have this requirement to initialise without the use of PostContruct. If you have time, can you please answer this one also: #27541073Blowtube

© 2022 - 2024 — McMap. All rights reserved.