Bindings

Linked Bindings

qianmoQqianmoQ· 更新于 2026-09-23· 阅读 3 分钟· 0 次阅读

登录后可跨设备保存划线和私人笔记登录

Linked Bindings

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

public class BillingModule extends AbstractModule {
  @Provides
  TransactionLog provideTransactionLog(DatabaseTransactionLog impl) {
    return impl;
  }
}

Now, when you call injector.getInstance(TransactionLog.class), or when the injector encounters a dependency on TransactionLog, it will use a DatabaseTransactionLog.

Linked bindings can also be chained:

public class BillingModule extends AbstractModule {
  @Provides
  TransactionLog provideTransactionLog(DatabaseTransactionLog databaseTransactionLog) {
    return databaseTransactionLog;
  }

  @Provides
  DatabaseTransactionLog provideDatabaseTransactionLog(MySqlDatabaseTransactionLog impl) {
    return impl;
  }
}

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

In addition to using @Provides method to created linked bindings, you can also use the bind method in Guice modules. For example, the following code links the concrete DatabaseTransactionLog class to a subclass:

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

评论

登录后参与评论

正在加载评论…