Google-Guice-1.一个对象的社会关系

wuhaixing 2011-06-15
用依赖注入,对象在他们的构建方法中获取其所依赖的对象。所以要构建一个对象,你得先构建其所依赖的对象,而这些对象又有自己所依赖的对象,不断深入。所以当你构建对象时,实际上是要构建一个完整的图(object graph)。

图不适合纯手工打造,累不说,还容易出错,不好测试。Guice是建图利器,你给他做些配置,他就能给你一个对象图。

举例说明, RealBillingService类的构造方法中有两个参数,他所依赖的接口 CreditCardProcessor 和 TransactionLog。把这个方法画上@Inject标记, Guice来的时候就知道这里有他的事。

class RealBillingService implements BillingService {
  private final CreditCardProcessor processor;
  private final TransactionLog transactionLog;

  @Inject
  RealBillingService(CreditCardProcessor processor, 
      TransactionLog transactionLog) {
    this.processor = processor;
    this.transactionLog = transactionLog;
  }

  @Override
  public Receipt chargeOrder(PizzaOrder order, CreditCard creditCard) {
    ...
  }
}


我们想要用PaypalCreditCardProcessor 和 DatabaseTransactionLog类实例来构建RealBillingService对象,可以声明一个module 告诉Guice用接口的哪个实现类,config里面是各种bind to:

public class BillingModule extends AbstractModule {
  @Override 
  protected void configure() {

     /*
      * This tells Guice that whenever it sees a dependency on a TransactionLog,
      * it should satisfy the dependency using a DatabaseTransactionLog.
      */
    bind(TransactionLog.class).to(DatabaseTransactionLog.class);

     /*
      * Similarly, this binding tells Guice that when CreditCardProcessor is used in
      * a dependency, that should be satisfied with a PaypalCreditCardProcessor.
      */
    bind(CreditCardProcessor.class).to(PaypalCreditCardProcessor.class);
  }
}


module 准备好!哒哒哒,Guice中的建图者Injector要出场了!首先我们create一个Injector,然后我们就可以get RealBillingService的Instance啦。

public static void main(String[] args) {
    /*
     * Guice.createInjector() takes your Modules, and returns a new Injector
     * instance. Most applications will call this method exactly once, in their
     * main() method.
     */
    Injector injector = Guice.createInjector(new BillingModule());

    /*
     * Now that we've got the injector, we can build objects.
     */
    RealBillingService billingService = injector.getInstance(RealBillingService.class);
    ...
  }


get RealBillingService的Instance的过程中,Guice创建了一个small的object graph,这个图里面包括billingService及其所需的CreditCardProcessor实例和
TransactionLog实例
Global site tag (gtag.js) - Google Analytics