My favorites | Sign in
Project Home Downloads Wiki Issues Source
Search
for
LinkedBindings  
Updated Oct 16, 2011 by sberlin

Linked Bindings

Linked bindings map a type to its implementation. This example maps the interface TransactionLog to the implementation DatabaseTransationLog:

public class BillingModule extends AbstractModule {
  @Override 
  protected void configure() {
    bind(TransactionLog.class).to(DatabaseTransactionLog.class);
  }
}

Now, when you call injector.getInstance(TransactionLog.class), or when the injector encounters a dependency on TransactionLog, it will use a DatabaseTransactionLog. Link from a type to any of its subtypes, such as an implementing class or an extending class. You can even link the concrete DatabaseTransactionLog class to a subclass:

    bind(DatabaseTransactionLog.class).to(MySqlDatabaseTransactionLog.class);

Linked bindings can also be chained:

public class BillingModule extends AbstractModule {
  @Override 
  protected void configure() {
    bind(TransactionLog.class).to(DatabaseTransactionLog.class);
    bind(DatabaseTransactionLog.class).to(MySqlDatabaseTransactionLog.class);
  }
}

In this case, when a TransactionLog is requested, the injector will return a MySqlDatabaseTransactionLog.

Comment by sanrod...@gmail.com, Oct 2, 2010

Linked bindings can also be chained or must be chained?

For example, this is correct?:

bind(TransactionLog?.class).to(MySqlDatabaseTransactionLog?.class);

Jump directly to the second subclass.

Comment by nick.z...@gmail.com, Dec 29, 2010

Can also be chained. Your example would work fine and is exactly what you would do 99% of the time.

Comment by brandhil...@gmail.com, May 23 (4 days ago)

First sentence, "DatabaseTransationLog?" should be "DatabaseTransactionLog?"


Sign in to add a comment
Powered by Google Project Hosting