marabol
marabol

Reputation: 1257

Is it possible to inject a list of beans implementing an interface using Java EE

I wonder, if I can inject a list of (stateless) beans, that all implementing a special interface.

For example I've a module contract

public interface ResetService {
  void reset(MyContext context);
}

Than I've two modules, that are implementing this interface. And one module, that should call all implementations:

@EJBs
private List<ResetService> resetServices;

void resetAllModules(MyContext context) {
  for (ResetService resetService : resetServices)
    resetService.reset(context);
}

It's important that all calls are in the main transaction and the reset caller must be know, if the reset call is complete. So I can't use JMS and topics.

I think, it's not possible, or?

Upvotes: 3

Views: 5283

Answers (3)

Vladimir Sosnin
Vladimir Sosnin

Reputation: 118

You can get all beans of type by:

    @Inject
    BeanManager beanManager;

    public Set<ResetService> getAllResetServices() {
       return beanManager.getBeans(ResetService.class);
    }

Upvotes: 2

Fireworks
Fireworks

Reputation: 515

Privious answer is wrong. You can inject dynamicaly using @Any annotation and javax.enterprise.inject.Instance class. Here simple example http://coders-kitchen.com/2013/01/24/jee-and-dynamic-dependency-injection/

Upvotes: 3

Pascal Thivent
Pascal Thivent

Reputation: 570355

Not possible with annotations. Your best option here is to loop over an array of JNDI names1 and to do a JNDI lookup for each to feed your List. Just in case, maybe have a look at previous questions like this one if you want to try to make things more dynamic (I'm not convinced it would be a good idea).

Upvotes: 2

Related Questions