在CDI中注入对象列表(焊接) [英] Inject list of objects in CDI (Weld)

查看:121
本文介绍了在CDI中注入对象列表(焊接)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个名为 SocialNetworkService 的接口,还有三个实现 - TwitterService FacebookService FriendFeedService

Let's say I have an interface called SocialNetworkService, and three implementations - TwitterService, FacebookService and FriendFeedService.

现在我想要,每当我的托管bean(或其他任何东西) web组件)接收消息,在所有社交网络中共享它。我试过了:

Now I want, whenever my managed bean (or whatever web component) receives a message, to share it in all social networks. I tried:

@Inject private List<SocialNetworkService> socialNetworkServices;

但它不起作用(部署错误)。 (也试过 @Any 限定符 - 结果相同)

But it didn't work (deployment error). (Also tried to the @Any qualifier - same result)

那么,有没有办法注入一个列表接口的所有(或某些)实现?

So, is there a way to inject a list of all (or some) implementations of an interface?

我知道给定注入点不应该有多个可能的bean的规则。我想我可以通过制作一个生成列表的制作人,并使用 Instance< SocialNetworkService> 来实现这一点,但这似乎对此任务来说太多了。

I know the rule that a given injection point should not have more than one possible bean. I guess I can achieve that by making a producer that produces the list, and using Instance<SocialNetworkService>, but that seems like too much for this task.

推荐答案

将我的尝试与Weld论坛的回答结合起来:

Combining my attempts with an answer from the Weld forum:

@Inject @Any
private Instance<SocialNetworkService> services;

实例实现 Iterable ,因此可以简单地使用for-each循环。需要 @Any 限定符。

Instance implements Iterable, so it is then possible to simply use the for-each loop. The @Any qualifier is needed.

另一种方法这是通过使用事件系统:

Another way to do this is by using the event system:


  • 创建一个 MessageEvent (包含所有有关消息的信息)

  • 而不是注入社交网络列表,只需注入事件:

  • create a MessageEvent (containing all the information about the message)
  • instead of injecting a list of social networks, simply inject the event:

@Inject private Event<MessageEvent> msgEvent;

并解雇它: msgEvent.fire(new MessageEvent(message));

观察所有服务中的事件(无论其界面如何,这可能都是加分):

observe the event in all services (regardless of their interface, which might be a plus):

public void consumeMessageEvent(@Observes MessageEvent msgEvent) {..}


这篇关于在CDI中注入对象列表(焊接)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆