简体   繁体   中英

Inject list of service objects in CDI (Weld)

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

Now I want, whenever my managed bean receives a message, to select one/or more implementations depending on certain rules contained within the message and transmit the message accordingdly.

I am not quite sure which would be the best pattern to use?

a) Use Interface Instance ie

@Inject @Any Instance<SocialNetworkService> socialNetworkService;
SocialNetworkService service = socialNetworkService.get();

How would I pass the message to the SocialNetworkServiceFactory ?

b) Use Events observe the event in all services (regardless of their interface, which is not exactly what i would like. Ie if i dont support dont transmit...

c). i could have annotaded injection ie @Twitter, @Facebook all in a controller bean and then select the appropriate but my service implementations number will grow....

Thanks in advance,

Dimitri

You can always use iterator in order to obtain all current implementations

Iterator<SocialNetworkService> it = socialNetworkService.iterator();
while(it.next()) {
    SocialNetworkService service = it.next();
    //here you can choose by some criterion if the service should receive message or not
    if(service instanceof TwitterNetworkService) {
         //do something
    }
}

The event/observer model is probably the most appropriate for you. You can fire an event with one or more qualifiers, each of those qualifiers could be tied to one of these services.

I would suggest to combine approach a) and b).

In your Managed Bean send out an Event of the desired type.

Now you will have a single Event observer for this specific event. This observer injects all available implementations of your SocialNetworkService.

Each implementation of a SocialNetworkService should now implement a accept method. This implies that you don't need to change the observer class, when new services are added.

The observer now iterates over all available instances and hands over the retrieved message (could be the event itself) to the accept method of each implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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