Evan Knowles
Evan Knowles

Reputation: 7501

Find all EJBs implementing interface

I have a set of data that is provided by multiple providers. As they each have their own ways of accessing it, they each have separate EJBs although they all implement the same interface.

Is there a way to have all of them injected? So that I end up with some sort of List<MyInterface>? Standard injection seems to give either one, or error on ambiguity.

Upvotes: 0

Views: 1587

Answers (1)

maress
maress

Reputation: 3533

With the CDI integration, you have two options, based on how you have organized your projects.

If the providers are defined within the same module, i.e. the injection is within the same war as the definition of the ejbs, or in the same ejb jar as in the declaration of the injection points, then:

public class MyService {

   @Inject
   @Any
   private Instance<MyProvider> providers;

   public void notifyProviders() {

     //Because there may be multiple implementation, do not use providers.get(), it is ambigous.
     //The Instance object implements Iterable, so you can iterate over it using the for loop.
     for(final MyProvider provider : providers) {
       provider.notify();
     }
   }
}

If however, you have remote definition of these ejbs, then you need to resolve to using @Producer, from whence you can use the above Instance injection, since CDI cannot inject remote ejb beans. Thus:

@Stateless
public class MyProviderContext {

   @EJB
   private MyProvider1 provider1;

   @EJB
   private MyProvider2 provider2;

   //... More declarations.

   @Produces
   public MyProvider provider1() {return provider1;}

   @Produces
   public MyProvider provider2() {return provider2;}

   //... More producers.
}

Upvotes: 6

Related Questions