DEV Community

Ashutosh Sharma
Ashutosh Sharma

Posted on

1 1

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

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay