我需要使用依賴注入來從某些ejb(無狀態和單例)引發事件。我不使用Spring,Guice等。 問題是,當通過getInstance()調用其方法時,我在其中一個bean中獲得NPE。以下是代碼片段:Singleton CDI @Inject空指針異常
@Stateless
@LocalBean
public class ControllerStartStop {
@Inject
private Event<SomeWebMessage> webEvent;
public String startCircle(String passwordP, String passwordH) {
.........
String res = "some msg";
webEvent.fire(new SomeWebMessage(res, 0)); // this works fine
MainDay.getInstance().startDay(); // NullPointerException
下面是MainDay單:
@Singleton
public class MainDay {
private static final MainDay mDay = new MainDay();
public static MainDay getInstance() { return mDay ; }
@Inject
private Event<SomeWebMessage> webEvent;
public void startDay() {
String s = new String("MainDay");
webEvent.fire(new SomeWebMessage(s,0)); // NullPointerException
beans.xml的是在META-INF:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.1" bean-discovery-mode="all">
</beans>
有當我從火災事件沒有NPE一個像MainDay.initDS()這樣的靜態方法的調用,或者當Sheduler調用方法startDay()時(@Schedule(hour =「」,minute =「」,second = 「/10」)*。 我不知道是什麼原因
謝謝托馬斯!現在,它清晰,它的工作原理:) – Buch