Getting multiple instances of a CDI bean

This is a simple and quick post to show you how to get multiple implementations of a single interface when you are using the CDI context or even EJB.

Let’s develop a sample interface with two basic implementations:

public interface SimpleService {

    String doSomething();

}
import javax.inject.Named;

@Named
public class SomeSimpleService implements SimpleService {

    @Override
    public String doSomething() {
        return "Some single service";
    }

}
import javax.inject.Named;

@Named
public class OtherSimpleService implements SimpleService {

    @Override
    public String doSomething() {
        return "Other single service";
    }

}

We must consider that you could have a lot more implementations of this interface. For some reason, in this case you have to use all the implementations and call a method of each one of them.

The keypoint to do this is to use the @Any annotation and the Instance interface.

An example of its use in a stateless EJB can be done this way:

import java.util.Iterator;

import javax.ejb.Stateless;
import javax.enterprise.inject.Any;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;

@Stateless
public class StatelessBean {

    @Inject @Any
    private Instance<SimpleService> simpleService;

    public void doSomethingWithAllSimpleServices() {
        Iterator<SimpleService> services = simpleService.iterator();
        while (services.hasNext()) {
            System.out.println(services.next().doSomething());
        }
    }

}

Very simple, right? 🙂

With this approach, you could also think in getting “any bean” of that type. For this, create another method in StatelessBean class:

[...]

    public void doSomethingWithAnySimpleService() {
        System.out.println(simpleService.get().doSomething());
    }

[...]

It’s just this for today. Hope it can help you.
See you soon.

Let me your thoughts