13

我有一个会话范围的 bean:

@Named
@SessionScoped
public class SessionBean implements Serializable {

    private String someProperty;

    public String getSomeProperty() {
        return someProperty;
    }

}

我想将它注入一个请求范围的bean并用它初始化:

@Named
@RequestScoped
public class RequestBean {

    @Inject
    private SessionBean sessionBean;  

    public RequestBean() {
        System.out.println(sessionBean.getProperty());
    }

}

但是,它会引发以下异常:

java.lang.NullPointerException
    at com.example.RequestBean.<init>(RequestBean.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 org.jboss.weld.introspector.jlr.WeldConstructorImpl.newInstance(WeldConstructorImpl.java:206)
    at org.jboss.weld.injection.ConstructorInjectionPoint.newInstance(ConstructorInjectionPoint.java:117)
    at org.jboss.weld.bean.ManagedBean.createInstance(ManagedBean.java:336)
    at org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget.produce(ManagedBean.java:200)
    at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:292)
    ...

这是如何引起的,我该如何解决?

4

2 回答 2

27

您期望注入的依赖项在构建 bean 之前可用。你期望它像这样工作:

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

然而,这不是真的,而且在技术上是不可能的。依赖项在构造后注入。

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

@PostConstruct如果您打算在 bean 构建后直接基于注入的依赖项执行业务逻辑,则应该使用一种方法。

删除构造函数并添加此方法:

@PostConstruct
public void init() {
    System.out.println(sessionBean.getSomeProperty());
}
于 2013-05-06T13:45:18.650 回答
1

BalusC 的回复是正确的,但确实反映了对象创建的分配阶段,此时没有运行。但是无论如何,CDI如果您grep通过以下方式以编程方式访问该 bean:

javax.enterprise.inject.spi.CDI.current().select(SessionBean.class).get()
于 2017-10-25T10:41:59.970 回答