Ich habe eine Sitzung scoped Bohne:Nullpointer beim Versuch @Inject Bean zuzugreifen in Konstruktor
@Named
@SessionScoped
public class SessionBean implements Serializable {
private String someProperty;
public String getSomeProperty() {
return someProperty;
}
}
Ich möchte diese scoped in einer Anfrage-Bean injizieren und initialisieren damit:
@Named
@RequestScoped
public class RequestBean {
@Inject
private SessionBean sessionBean;
public RequestBean() {
System.out.println(sessionBean.getProperty());
}
}
Allerdings wirft es die folgende Ausnahme:
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)
...
Wie wird diese verursacht und wie kann ich sie lösen?
Die Abhängigkeit kann nur injiziert werden, sobald die Instanziierung erfolgt ist, aber Sie verwenden sie im Konstruktor. Versuchen Sie, den Code beim Post-Construction auszuführen. –
tat ich. gleiches Ergebnis. –
Ich glaube, Sie haben den "Post-Construction" -Teil nicht verstanden. Sie sollten eine @ PostConstruct-Methode verwenden und sie absolut nicht innerhalb des Konstruktors aufrufen. – BalusC