Guice:使用提供者获取多个实例:

Guice: Using providers to get multiple instances:

我正在尝试使用 Provider 学习 Guice 的依赖注入来创建一个对象的多个实例(示例来自 Guice 网站上的入门指南)。我应该如何测试这个?请指教

模块如下:

package testing;

import com.google.inject.AbstractModule;

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

以下为class待测:

package testing;
import com.google.inject.Inject;
import com.google.inject.Provider;

public class RealBillingService implements BillingService {
  private  Provider<CreditCardProcessor> processorProvider;
  private  Provider<TransactionLog> transactionLogProvider;

  @Inject
  public RealBillingService(Provider<CreditCardProcessor> processorProvider,
      Provider<TransactionLog> transactionLogProvider) {
    this.processorProvider = processorProvider;
    this.transactionLogProvider = transactionLogProvider;
  }

  public void chargeOrder() {
    CreditCardProcessor processor = processorProvider.get();
    TransactionLog transactionLog = transactionLogProvider.get();

    /* use the processor and transaction log here */
    processor.toString();
    transactionLog.toString();

  }
}

以下是测试 class 与 main():

public class test {
public static void main(String[] args) {

        Injector injector = Guice.createInjector(new BillingModule());
        BillingService billingService = injector.getInstance(BillingService.class);

        billingService.chargeOrder();   
      }
}

在 运行 之后,我希望显示以下 toString 方法的输出,但什么也没看到:

    processor.toString();
    transactionLog.toString();

我在这里错过了什么?

请指教,

谢谢!

发生这种情况是因为您只是调用了 toString 而没有将结果字符串放在任何地方(例如调用 System.out.println)

然而,提供者不应该被这样使用。您不应该自己调用 Provider.get:而是需要提供者的结果,注册您的提供者并让 Guice 完成它的工作(您也可以使用 @Provides 在模块中注释方法而不是定义提供者 classes )

默认情况下,每次需要某个 class 的新实例时都会调用提供程序。除非您通过使用范围(如内置单例)明确请求,否则不会回收实例