Pergunta

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());     
}
Foi útil?

Solução

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());
}

Outras dicas

That's the expected behaviour.

@PostConstruct method is executed right after bean's construction and injection of dependencies, such as @ManagedProperty, has taken place. So your dependencies simply won't be available in constructor.

What you need to do it to annotate a method with @PostConstruct and refer to your dependencies is a standard manner:

@PostConstruct
public void init() {
    injectedDependency.performOperation();
}
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top