Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
764 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...