Inject list of objects in CDI (Weld)
Combining my attempts with an answer from the Weld forum:
@Inject @Any
private Instance<SocialNetworkService> services;
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:
- 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;
and fire it:
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) {..}
![Bozho](https://i.stack.imgur.com/07ej2.jpg?s=256&g=1)
Bozho
Bozhidar Bozhanov - Senior Java developer (CV | Web CV) Creator of: https://logsentinel.com/ (LogSentinel SIEM) https://logsentinel.com/sentineldb (GDPR-compliant, privacy-by-design datastore) http://computoser.com (algorithmic music generation)
Updated on June 06, 2022Comments
-
Bozho about 2 years
Let's say I have an interface called
SocialNetworkService
, and three implementations -TwitterService
,FacebookService
andFriendFeedService
.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;
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?
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. -
Bozho over 13 yearsthat would be even more tedious than the my initial suggestion. Thanks anyway.
-
matbrgz over 13 yearsThe initial suggestion still needs to know about all your implementations - Weld cannot as far as I can see tell you.
-
Tair over 12 years@Bozho The find-all-instances approach looks like an anti-pattern with a well-known-but-not-obvious solution using Events
-
Bozho over 12 yearswell, I think both are valid. The first means more coupling, indeed, but is, for example, easier to trace later. It depends on your objectives.
-
Laird Nelson over 7 years(Ancient subject, I know, but also be aware of issues.jboss.org/browse/CDI-535: the ordering of
@Inject @Any Instance<Something> stuff;
is not guaranteed.)