尝试访问托管bean构造函数中的@EJB bean时出现NullPointerException

时间:2013-05-20 16:27:05

标签: jsf constructor nullpointerexception ejb managed-bean

我有一个EJB服务。

@Stateless
public class SomeService {}

我想将它注入一个viewscoped bean并用它初始化:

@ManagedBean
@ViewScoped
public class ViewBean implements Serializable {

    @EJB
    private SomeService someService;

    public ViewBean() {
        System.out.println(someService.getEntity());
    }

}

但是,它会抛出以下异常:

com.sun.faces.mgbean.ManagedBeanCreationException: Cant instantiate class: com.example.ViewBean.
    at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:193)
    at com.sun.faces.mgbean.BeanBuilder.build(BeanBuilder.java:102)
    at com.sun.faces.mgbean.BeanManager.createAndPush(BeanManager.java:409)
    at com.sun.faces.mgbean.BeanManager.create(BeanManager.java:269)
    at com.sun.faces.el.ManagedBeanELResolver.resolveBean(ManagedBeanELResolver.java:244)
    at com.sun.faces.el.ManagedBeanELResolver.getValue(ManagedBeanELResolver.java:116)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    [snip]
Caused by: java.lang.NullPointerException
    at com.example.ViewBean.<init>(ViewBean.java:42)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:525)
    at java.lang.Class.newInstance0(Class.java:374)
    at java.lang.Class.newInstance(Class.java:327)
    at com.sun.faces.mgbean.BeanBuilder.newBeanInstance(BeanBuilder.java:188)
    ... 62 more

这是如何引起的?如何解决?

1 个答案:

答案 0 :(得分:3)

换句话说,您期望EJB注入工作如下:

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

然而,这在技术上是不可能的。当根本没有构造实例时,不可能分配实例变量。

在构造之后直接基于注入的依赖关系执行任务的规范方法是使用@PostConstruct带注释的方法。

因此,要解决您的具体问题,只需替换

即可
public ViewBean() {

通过

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

通过这种方式,这个过程将大致如下:

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

请注意,具体问题与视图范围完全无关。使用请求,会话或应用程序作用域bean时,您遇到了完全相同的问题。因此,这是另一个证据,表明您从未通过使用不同范围进行测试而将其排除在原因之外。