Hobione's Weblog

Living & Breathing in Web 2.0 Era

JSF @PostConstruct

Scenario:  I needed to get some data for datatable when the bean get initiated.
So, I have tried these following code.

public TrainingClassForm() {  //constructor
        this.trainingListModel.getAllTrainingClasses();
    }

Error:

me:  javax.faces.FacesException: Problem in renderResponse: javax.faces.FacesException: Cant instantiate class: gov.faa.amc.nas.hrtrainingview.bean.backing.TrainingClassForm.. null

Issue: Banging my head after few hours, then I have discussed with JSF Expert, Jason Lee who helped me to sort this out.   I was calling trainingListModel before it get initiated/born.  So I was getting a null pointer in TrainingListModel class.

Lesson to learn:  Use @PostConstruct instead.

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

// Constructor
    public TrainingClassForm() {

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

    }

2. @PreDestroy:Any scoped managed bean menthod annotated with @PreDestroy will be called before the bean is removed from the scope or before the scope in which the bean resides is destroyed, whichever comes first.  The constraints placed on the method are the same as with @PostConstruct.

Ref Book: The Complete Reference – JavaServerFaces  by Chris Schalk & Ed Burns

April 22, 2009 Posted by HobiOne | Java Server Faces | | No Comments Yet