NullPointerException while trying to access @Inject bean in constructor

You’re expecting that the injected dependency is available before the bean is constructed. You’re expecting that it works like this:

RequestBean requestBean;
requestBean.sessionBean = sessionBean; // Injection.
requestBean = new RequestBean(); // Constructor invoked.

This is however not true and technically impossible. The dependencies are injected after construction.

RequestBean requestBean;
requestBean = new RequestBean(); // Constructor invoked.
requestBean.sessionBean = sessionBean; // Injection.

You should be using a @PostConstruct method instead if you intend to perform business logic based on injected dependencies directly after bean’s construction.

Remove the constructor and add this method:

@PostConstruct
public void init() {
    System.out.println(sessionBean.getSomeProperty());
}

Leave a Comment