NullPointerException while trying to access @EJB bean in managed bean constructor

前端 未结 1 1541
逝去的感伤
逝去的感伤 2021-01-27 00:42

I\'ve an EJB service.

@Stateless
public class SomeService {}

I\'d like to inject this in a viewscoped bean and initialize with it:



        
相关标签:
1条回答
  • 2021-01-27 01:17

    In other words, you're expecting that EJB injection works under the covers as follows:

    ViewBean viewBean;
    viewBean.someService = new SomeService(); // EJB injected, so that constructor can access it.
    viewBean = new ViewBean(); // ViewBean constructed.
    

    However, this is technically impossible. It's not possible to assign an instance variable when the instance isn't been constructed at all.

    The canonical approach to perform a task based on injected dependencies directly after construction is to use a @PostConstruct annotated method.

    So, to fix your concrete problem, just replace

    public ViewBean() {
    

    by

    @PostConstruct
    public void init() { // Note: Method name is fully free to your choice.
    

    This way the process would under the covers be roughly as follows:

    ViewBean viewBean;
    viewBean = new ViewBean(); // ShiftBean constructed.
    viewBean.someService = new SomeService(); // EJB injected.
    viewBean.init(); // PostConstruct invoked.
    

    Please note that the concrete problem has completely nothing to do with the view scope. You'd have had exactly the same problem when using a request, session or application scoped bean. This is thus another evidence that you have never actually excluded it from being the cause by testing using a different scope.

    0 讨论(0)
提交回复
热议问题