My favorites | Sign in
Google
                
Search
for
Updated Mar 02, 2009 by limpbizkit
ProvidesMethods  

@Provides Methods

When you need code to create an object, use an @Provides method. The method must be defined within a module, and it must have an @Provides annotation. The method's return type is the bound type. Whenever the injector needs an instance of that type, it will invoke the method.

public class BillingModule extends AbstractModule {
  @Override
  protected void configure() {
    ...
  }

  @Provides
  TransactionLog provideTransactionLog() {
    DatabaseTransactionLog transactionLog = new DatabaseTransactionLog();
    transactionLog.setJdbcUrl("jdbc:mysql://localhost/pizza");
    transactionLog.setThreadPoolSize(30);
    return transactionLog;
  }
}

If the @Provides method has a binding annotation like @PayPal or @Named("Checkout"), Guice binds the annotated type. Dependencies can be passed in as parameters to the method. The injector will exercise the bindings for each of these before invoking the method.

  @Provides @PayPal
  CreditCardProcessor providePayPalCreditCardProcessor(
      @Named("PayPal API key") String apiKey) {
    PayPalCreditCardProcessor processor = new PayPalCreditCardProcessor();
    processor.setApiKey(apiKey);
    return processor;
  }

Comment by bluepenguin, Apr 25, 2009

This only works with Guice 2.

Comment by limpbizkit, Oct 11, 2009

You can also annotate the method with a scope, like @Singleton or @RequestScoped.

Comment by gili.tzabari, Oct 13, 2009

limpbizkit,

Excellent point, but I suggest you update the wiki document with such an example in case users skip the comments.


Sign in to add a comment