【译】Guice-LinkedBindings

Linked Bindings

Linked Bindings将类型映射到其实现。下面这个例子将接口TransactionLog映射到其实现DatabaseTransactionLog:

1
2
3
4
5
6
public class BillingModule extends AbstractModule {
@Override
protected void configure() {
bind(TransactionLog.class).to(DatabaseTransactionLog.class);
}
}

当您调用inject.getInstance(TransactionLog.class)时,或者当注入器遇到对TransactionLog的依赖时,它将使用DatabaseTransactionLog。某类型绑定到其任何子类型,例如实现类或扩展类。甚至可以将具体的DatabaseTransactionLog类绑定到一个子类:

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

写法:

1
2
3
4
5
6
7
    public class BillingModule extends AbstractModule {
@Override
protected void configure() {
bind(TransactionLog.class).to(DatabaseTransactionLog.class);
bind(DatabaseTransactionLog.class).to(MySqlDatabaseTransactionLog.class);
}
}

在这种情况下,当使用TransactionLog时,注入器将返回MySqlDatabaseTransactionLog实例。