DEV Community

Ashutosh Sharma
Ashutosh Sharma

Posted on

How to inject all implementations of an Interface?

How to inject all implementations of an Interface?

Suppose you have multiple implementations of an Interface and you want all the implementations injected.

For example:

Handler is an Interface and it has three implementations.

public interface Handler {
    String handle();
}
Enter fullscreen mode Exit fullscreen mode

All the implementation needs to be marked for @ApplicationScoped like:

import javax.enterprise.context.ApplicationScoped;

@ApplicationScoped
public class PrintHandler implements Handler {
    public String handle() {
        return "PrintHandler";
    }
}
Enter fullscreen mode Exit fullscreen mode

In the class where you want to inject all the implementations, use

@Inject
Instance<Handler> handlers;
Enter fullscreen mode Exit fullscreen mode

This Instance is imported from javax.enterprise.inject.Instance;

This handlers the variable will have all the implementations of Handler interface.

javax.enterprise.inject.Instance also implements the Iterable so you can iterate to it and call the required methods.

@Inject
Instance<Handler> handlers;

@GET
@Produces(MediaType.TEXT_PLAIN)
public List<String> handle() {
    List<String> list = new ArrayList<>();
    handlers.forEach(handler -> list.add(handler.handle()));
    return list;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)