如何在焊接中使用事件(cdi)

how to use event in weld (cdi)

我正在研究 jboss weld event tutorialWeld Event,我想写一个例子来观察一个事件并在它被触发时打印 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)

容器中似乎没有beans可以初始化

Event<MyEvent> events;

那我应该怎么做才能做到呢运行,我的 beans.xml 为空

基本上,您的代码失败是因为您没有使用 class 的托管实例。这是一个更好的方法

@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 中启动容器,并使用对 class 的托管引用。注入点仅在您使用托管引用时得到解决。