Constructor bindings

This kind of binding binds a type to a constructor. This specific case arises when the @Inject annotation can't be implemented to the target constructor. Possible reasons for this could be:

  • If we are using a third-party class
  • A couple of constructors taking part in dependency injection

To address such a problem, we have the toConstructor() binding in our module. Here, if the constructor cannot be found, module reflectively select our target constructor and handle the exception:

public class SampleModule extends AbstractModule {
  @Override 
  protected void configure() {
    try {
      bind(NotificationService.class).toConstructor(
          SMSService.class.getConstructor(SMSDatabaseConnection.class));
    } catch (NoSuchMethodException e) { ...

Get Java 9 Dependency Injection now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.