【译】Guice-Getting Started

使用依赖注入,对象在其构造函数中接受依赖关系。要构建一个对象,你首先构建它的依赖。但是要构建每个依赖关系,您需要其相关依赖,依此类推。所以当你建立一个对象时,你真的需要建立一个对象关系图。

手工构建对象关系图是劳动密集型,容易出错的,使测试变得困难。Guice可以帮你构建对象图。但首先,Guice需要配置为完全按照需要构建对象关系图。

为了说明,我们将启动BillingService类,它在其构造函数中接受它的依赖接口CreditCardProcessor和TransactionLog。为了明确指出Guice调用BillingService构造函数,我们添加了@Inject注释:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class BillingService {
private final CreditCardProcessor processor;
private final TransactionLog transactionLog;

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

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

我们要使用PaypalCreditCardProcessor和DatabaseTransactionLog构建一个BillingService。 Guice使用绑定来将类型映射到它们的实现。 一个模块是使用链式的方法调用指定的绑定集合:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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);
}
}

模块是注入器的构建块,它是Guice的对象图构建器。 首先我们创建注入器,然后我们可以使用它来构建BillingService:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
  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.
*/

BillingService billingService = injector.getInstance(BillingService.class);
...
}

通过构建billingService,我们使用Guice构建了一个小对象图。 该图包含计费服务及其相关的信用卡处理器和事务日志。