1

Need help with the Dependency injection using guice in Dropwizard.

public class VendorHandlerFactory {

    private static final Logger LOGGER = LoggerFactory.getLogger(VendorHandlerFactory.class);

    private final Map<Vendor, VendorHandler> vendorHandlerMap;

    @Inject
    public VendorHandlerFactory(final Set<VendorHandler> vendorHandlers) {
        vendorHandlerMap = Maps.uniqueIndex(vendorHandlers, VendorHandler::getVendorType);
    }

    public VendorHandler getVendorHandler(final Vendor vendor) {
        VendorHandler vendorHandler = vendorHandlerMap.get(vendor);
        if (vendorHandler == null) {
           // do something
        }
        return vendorHandler;
    }
}

Vendor is enum and VendorHandler is an interface. I have VendorA implementing VendorHandler.

I am stuck with dependency injection. Getting below error :

2) [Guice/MissingImplementation]: No implementation for Set<VendorHandler> was bound.

Requested by:
1  : VendorHandlerFactory.<init>
      \_ for 1st parameter
     at GuiceModule.configure(GuiceModule.java)
      \_ installed by: Elements$ElementsAsModule -> GuiceModule
hmims
  • 539
  • 8
  • 28

1 Answers1

1

I assume you want to register multiple VendorHandler implementations in different guice modules and inject all of them in VendorHandlerFactory. But guice is very strict and can't gather all registered implementations autiomatically (as spring). You need to manually describe each implementation as part of a set with guice multibindings:

Multibinder.newSetBinder(binder(), VendorHandler.class);
uriBinder.addBinding().to(VendorA.class)

Note that it is ok to call Multibinder.newSetBinder for each implementation registration (in each guide module where registration is required).

Only after that you can inject Set<VenderHandler> with all registered implementations.

Also, you can use a MapBinder to bind handlers as map to be able to inject it as Map<Vendor, VendorHandler> without manual convertation

xvik
  • 346
  • 1
  • 5