jsf-2managed-beanmanaged-property

Accessing session bean data in constructor of JSF managed bean


I am trying to access the session bean data in the managed bean constructor. For that purpose I am using @ManagedProperty annotation as below. When I try to access in constructor it gives java.lang.NullPointerException and the same piece of code is accessible in another function. May be I need to do something different for constructor. Could someone please guide me what I need to do.

@ManagedProperty(value="#{sessionBean}")
private SelectCriteriaBean sessionData; 

// This is contructor
public ModifyBusinessProcessBean() {
  logger.debug(getSessionData().getSelectedBusinessProcessLevelZero());     
}

// Another Function where the same code doesn't give error
public anotherFunction() {
  logger.debug(getSessionData().getSelectedBusinessProcessLevelZero());     
}

Solution

  • You should not use @ManagedProperty inside constructor as it is not yet set. When managed bean is created first its constructor is called, and then managed properties are set with setters. You should use method annotated with @PostConstruct as it is called after properties are set:

    @PostConstruct
    public void init() {
      logger.debug(getSessionData().getSelectedBusinessProcessLevelZero());
    }