NullPointerException while trying to access @Inject bean in constructor

爱⌒轻易说出口 提交于 2019-11-27 01:38:16

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

BalusC's reply is correct, but is does reflect the assignment phase of a object creation, that did not run at this time. But anyway the CDI bean should be accessible if you grep it programatically via:

javax.enterprise.inject.spi.CDI.current().select(SessionBean.class).get()
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!