views:

62

answers:

3

When I am inside the constructor of a managed and trying to reach out to other methods from other beans, I got java.lang.NullPointerException. Is there some kind of specification that not allow managed bean to do that?

@ManagedProperty(value="#{document}")
private DisplayListController document;

@EJB
DocumentSBean sBean;

public NewUserController() {
    document.list();
} 

Above I just do regular bean injection, nothing fancy. document is a SessionScoped managed bean that has method list() which just return a String. NewUserController is a RequestScoped managed bean.

+5  A: 

You should look into @PostConstruct. An example can be found here.

Your properties are not being set when you're trying to access them. You need to wait for them to be set. Bean management typically goes:

  1. Create Beans
  2. Set Properties

You're trying to use properties that have not been set, thus resulting in your NPE.

So your code could change to:

public NewUserController() { }

@PostConstruct
public void init() {
    document.list();
}
SB
thank you very much
Harry Pham
my pleasure - glad it worked for ya
SB
+1  A: 

There is no way the bean property could have been injected before the constructor is called, so the property must be null at that stage.

As answered by SB, lifecycle annotations like @PostConstruct or @PreDestroy are the way to go.

seanizer
A: 

DisplayListController should probably be configured to call its own init method with the @PostConstruct annotation on the list method

mR_fr0g