尝试在构造函数中访问 @Inject bean 时出现 NullPointerException [英] 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());
}
这篇关于尝试在构造函数中访问 @Inject bean 时出现 NullPointerException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!