Find all EJBs implementing interface

元气小坏坏 提交于 2019-12-11 18:39:32

问题


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.


回答1:


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.
}


来源:https://stackoverflow.com/questions/28380675/find-all-ejbs-implementing-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!