gpt4 book ai didi

jsf - 尝试在构造函数中访问 @Inject bean 时出现 NullPointerException

转载 作者:行者123 更新时间:2023-12-04 00:22:04 24 4
gpt4 key购买 nike

我有一个 session 范围的 bean:

@Named
@SessionScoped
public class SessionBean implements Serializable {

private String someProperty;

public String getSomeProperty() {
return someProperty;
}

}

我想将它注入(inject)一个请求范围的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)
...

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

最佳答案

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

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

然而,这不是真的,而且在技术上是不可能的。依赖项在构造后注入(inject)。
RequestBean requestBean;
requestBean = new RequestBean(); // Constructor invoked.
requestBean.sessionBean = sessionBean; // Injection.

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

删除 构造函数并添加此方法:
@PostConstruct
public void init() {
System.out.println(sessionBean.getSomeProperty());
}

关于jsf - 尝试在构造函数中访问 @Inject bean 时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16399974/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com