NullPointerException尝试访问@Inject bean在构造函数 [英] NullPointerException while trying to access @Inject bean in constructor
问题描述
我有一个会话作用域bean:
I've a session scoped bean:
@Named
@SessionScoped
public class SessionBean implements Serializable {
private String someProperty;
public String getSomeProperty() {
return someProperty;
}
}
在请求作用域bean中并用它初始化:
I'd like to inject this in a request scoped bean and initialize with it:
@Named
@RequestScoped
public class RequestBean {
@Inject
private SessionBean sessionBean;
public RequestBean() {
System.out.println(sessionBean.getProperty());
}
}
但是,它会抛出以下异常:
However, it throws the following exception:
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)
...
这是如何引起的,我该如何解决?
How is this caused and how can I solve it?
推荐答案
您期望在构造bean之前注入的依赖关系可用。您期望它的工作方式如下:
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.
您应该使用 @PostConstruct
方法,而不是直接在bean构造之后基于注入的依赖性执行业务逻辑
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());
}
这篇关于NullPointerException尝试访问@Inject bean在构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!