Upload page content

You can upload content for the page named below. If you change the page name, you can also upload content for another page. If the page name is empty, we derive the page name from the file name.

File to load page content from
Page name
Comment

Locked History Actions

guice/Manual/UserGuide/Bindings/ProviderBindings

Providerバインディング

@Providesメソッドが複雑になりはじめると、それを独立したクラスに移動したくなる。 Guiceの提供する、シンプルで一般的なインターフェースであるProviderインターフェースを実装したクラスとすればよい。

public interface Provider<T> {
  T get();
}

Our provider implementation class has dependencies of its own, which it receives via its @Inject-annotated constructor. It implements the Provider interface to define what's returned with complete type safety:

public class DatabaseTransactionLogProvider implements Provider<TransactionLog> {
  private final Connection connection;

  @Inject
  public DatabaseTransactionLogProvider(Connection connection) {
    this.connection = connection;
  }

  public TransactionLog get() {
    DatabaseTransactionLog transactionLog = new DatabaseTransactionLog();
    transactionLog.setConnection(connection);
    return transactionLog;
  }
}

このプロバイダを.toProvider句に指定する。

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

プロバイダが複雑な場合にはテストを忘れないこと!