CDI2.0 为什么 BeanManager 不能触发异步事件?

CDI2.0 Why can't the BeanManager fire Async Events?

我正在测试新的 CDI2.0 预发布版,我希望 BeanManager 能够异步触发事件。

CDI 1.2 我是这样做的:

@Inject
BeanManager beanManager;

public void fireEvents() {
        for (int i = 0; i < 10; i++) {
            beanManager.fireEvent(new LightEvent("Light Event " + i));
            beanManager.fireEvent(new HeavyEvent("Heavy Event " + i));
        }
    } 

由于我想测试 异步事件,我看到 BeanManager 没有 fireAsync() 方法。相反,我必须以其他方式触发事件:

@Inject
private Event<LightEvent> lightEvent;

@Inject
private Event<HeavyEvent> heavyEvent;

public void fireAsyncEvents() {
    for (int i = 0; i < 10; i++) {
        lightEvent.fireAsync(new LightEvent("light " + i));
        heavyEvent.fireAsync(new HeavyEvent("heavy " + i));
    }
}

现在一切正常,但我必须先定义事件。 是否计划向 Beanmanager 添加 fireAsync() 方法?

因为决定不让 BeanManager (BM) 膨胀那么多。为了进一步详细说明,有人要求 fireAsync 以及有人要求选择直接从 BM 触发事件,并选择限定符或类型,或类型和限定符。所有这些都是 有效要求 但是将所有这些添加到 BM 会使这个 "uber" 入口点变得更加膨胀。

因此,我们决定改为创建 BeanManager#getEvent(),您可以从中直接进入 Event 界面。从那里你可以根据所需的qualifiers/types(或保留默认值)执行select(..),然后你fire(对于同步事件)或fireAsync(对于异步)。

为了支持我上面的说法,你可以直接阅读相关的CDI issue or check the pull request

所以你想要的已经存在了,可能看起来像这样:

@Inject
BeanManager bm;

public void myMethod() {
  // default one
  bm.getEvent().fireAsync(new MyPayload());
  // with selections of subtype and qualifiers
  bm.getEvent().select(MyType.class, MyQualifier.class).fireAsync(new MyPayload());
}