3

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?

Arjan Tijms
  • 37,782
  • 12
  • 108
  • 140
marabol
  • 1,247
  • 2
  • 15
  • 22

3 Answers3

3

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/

Fireworks
  • 505
  • 2
  • 11
  • 1
    I think the question was about EJBs. And your blogposts shows the usage of the CDI annotations. The usage and handling on the serverside are totally different between CDI and EJB. – Waldemar Schneider Nov 13 '14 at 10:55
  • 1
    Previous answer was not wrong 4 years ago. With the latest J2EE spec (version 6) CDI was added which offers a solution. – Konstantin Feb 13 '15 at 08:18
  • The link you posted is dead; here is the archived snapshot: https://web.archive.org/web/20200725142516/http://coders-kitchen.com/2013/01/24/jee-and-dynamic-dependency-injection/ – Kajzer Nov 23 '21 at 07:09
2

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

Community
  • 1
  • 1
Pascal Thivent
  • 562,542
  • 136
  • 1,062
  • 1,124
2

You can get all beans of type by:

    @Inject
    BeanManager beanManager;

    public Set<ResetService> getAllResetServices() {
       return beanManager.getBeans(ResetService.class);
    }
  • BeanManager.getBeans returns Set> so it's not a solution. More info here https://docs.oracle.com/javaee/7/api/javax/enterprise/inject/spi/BeanManager.html – I.R. Dec 16 '21 at 15:52