My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
ToConstructorBindings  

Guice3
Updated Oct 16, 2011 by sberlin

Constructor Bindings

New in Guice 3.0

Occasionally it's necessary to bind a type to an arbitrary constructor. This comes up when the @Inject annotation cannot be applied to the target constructor: either because it is a third party class, or because multiple constructors that participate in dependency injection. @Provides methods provide the best solution to this problem! By calling your target constructor explicitly, you don't need reflection and its associated pitfalls. But there are limitations of that approach: manually constructed instances do not participate in AOP.

To address this, Guice has toConstructor() bindings. They require you to reflectively select your target constructor and handle the exception if that constructor cannot be found:

public class BillingModule extends AbstractModule {
  @Override 
  protected void configure() {
    try {
      bind(TransactionLog.class).toConstructor(
          DatabaseTransactionLog.class.getConstructor(DatabaseConnection.class));
    } catch (NoSuchMethodException e) {
      addError(e);
    }
  }
}

In this example, the DatabaseTransactionLog must have a constructor that takes a single DatabaseConnection parameter. That constructor does not need an @Inject annotation. Guice will invoke that constructor to satisfy the binding.

Each toConstructor() binding is scoped independently. If you create multiple singleton bindings that target the same constructor, each binding yields its own instance.

Comment by moe...@gmail.com, Dec 31, 2011

There's no toConstructor on AbstractModule? or even AbstractAndroidModule?. Where is toConstructor method??

Comment by pib.oliv...@gmail.com, Jan 6, 2012

It's very unclear what the benefits of Constructor bindings are compared to providers/provides methods other than they take part in AOP.

Comment by btus...@google.com, Jan 12, 2012

How to handle the situation when the constructor of a class in the third party library takes a parameter that is not a part of the injection process and has to be provided explicitly?


Sign in to add a comment
Powered by Google Project Hosting