我正在研究来自jboss weld event tutorial的焊接事件,我想编写一个示例来观察事件并在触发时打印helloword。
这是我的代码:
//MyEvent when it was fired, print HelloWorld
public class MyEvent{}
//observe MyEvent and when it happen print HelloWorld
public class EventObserver {
public void demo(@Observes MyEvent event){
System.out.println("HelloWorld");
}
}
//Main Class fire Event in demo method
public class EventTest {
@Inject @Any Event<MyEvent> events;
public void demo(){
Weld weld = new Weld();
WeldContainer container = weld.initialize();
events.fire(new MyEvent());
container.shutdown();
}
public static void main(String[] args){
EventTest test = new EventTest();
test.demo();
}
}
它不起作用并提供以下异常信息:
Exception in thread "main" java.lang.NullPointerException
at weldLearn.event.EventTest.demo(EventTest.java:18)
at weldLearn.event.EventTest.main(EventTest.java:24)
似乎容器中没有 bean 可以初始化
Event<MyEvent> events;
然后我应该怎么做让它运行,我的 beans.xml 为空
答案 0 :(得分:0)
基本上,您的代码失败了,因为您没有使用类的托管实例。这是一个更好的方法
@ApplicationScoped
public class EventTest {
@Inject Event<MyEvent> events;
public void demo(){
events.fire(new MyEvent());
}
public static void main(String[] args){
Weld weld = new Weld();
WeldContainer container = weld.initialize();
EventTest test = container.select(EventTest.class).get();
test.demo();
container.shutdown();
}
}
您在main中启动容器,并使用对您的类的托管引用。注入点仅在您使用托管引用时解决。