How to inject all implementations of an Interface?
Ashutosh Sharma

Ashutosh Sharma @ashusharmatech

About: 📚 Tech explorer and knowledge seeker. From coding adventures to the latest gadgets, I'm here to share my experiences and discoveries in the world of technology.

Location:
Pune, India
Joined:
Jul 6, 2020

How to inject all implementations of an Interface?

Publish Date: May 8 '22
3 0

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

Comments 0 total

    Add comment