简体   繁体   English

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

[英]how to use event in weld (cdi)

I am studying Weld Event from jboss weld event tutorial and I want to write an example which observes an event and print helloword when it was fired. 我正在从jboss焊接事件教程中研究Weld Event ,我想编写一个观察事件并在触发事件时打印helloword的示例。

this is my code: 这是我的代码:

//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();
    }
}

it doesnt work and give below exception info: 它不起作用,并在下面给出异常信息:

Exception in thread "main" java.lang.NullPointerException
       at weldLearn.event.EventTest.demo(EventTest.java:18)
       at weldLearn.event.EventTest.main(EventTest.java:24)

it seems that there are no beans in container which can initialize 似乎容器中没有可以初始化的bean

Event<MyEvent> events;

Then what should I do to make it running, my beans.xml is empty 然后我应该怎么做才能使其运行,我的beans.xml为空

  • Maybe I should do something in beans.xml ? 也许我应该在beans.xml中做些什么?
  • or I should write a java class implements Event interface ? 还是我应该写一个Java类实现Event接口
    anything will be apprecited. 任何事情都会令人感激。

Basically, your code fails because you're not using a managed instance of your class. 基本上,您的代码会失败,因为您没有使用类的托管实例。 Here's a better way to do it 这是一个更好的方法

@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();
  }
}

You start the container in main, and use a managed reference to your class. 您在main中启动容器,并使用对类的托管引用。 Injection points are only resolved when you're using managed references. 仅当您使用托管引用时才解析注入点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM