リンクバインディング
リンクバインディングは、タイプを実装にマップする。 この例ではTransactionLogインターフェースをDatabaseTransationLog実装にマップしている。
public class BillingModule extends AbstractModule {
@Override
protected void configure() {
bind(TransactionLog.class).to(DatabaseTransactionLog.class);
}
}さて、injector.getInstance(TransactionLog.class)と呼び出したり、あるいはインジェクタがTransactionLog依存を見つけたりすると、そこでDatabaseTransactionLogが使われる。 リンクは、あるタイプのサブタイプも可能である、実装クラスや拡張クラスといったものである。 コンクリートなDatabaseTransactionLogをそのサブクラスにリンクすることも可能だ。
訳注:インターフェースを実装クラスにマップすることだけができるわけではなく、要するにどのような型でもマップ元に指定できるということ。
bind(DatabaseTransactionLog.class).to(MySqlDatabaseTransactionLog.class);
リンクバインディングはチェーンすることもできる。
public class BillingModule extends AbstractModule {
@Override
protected void configure() {
bind(TransactionLog.class).to(DatabaseTransactionLog.class);
bind(DatabaseTransactionLog.class).to(MySqlDatabaseTransactionLog.class);
}
}この場合、TransactionLogが要求されると、インジェクタはMySqlDatabaseTransactionLogを返す。
