Getting Started
对象可以通过依赖注入的方式在构造函数中它所依赖的对象。一般而言,为了构造一个对象,要先构造它依赖的对象。但是,为了构造这些依赖对象,又需要构造其他一些依赖对象。如此循环下来,实际上是构造了一个对象依赖关系图(object graph
)1。
手动构造对象依赖关系图是一件吃力不讨好的事情,容易出错并且不利于代码测试。Guice可以帮你完成这个工作,但是在使用前需要进行恰当的配置。
为了说明的方便,我们假设有一个类BillingService
,它需要通过构造函数引入两个依赖对象CreditCardProcessorh
和TransactionLog
。我们通过添加@Inject
注解来显示表明BillingService
是通过Guice进行依赖注入的:
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) {
...
}
}
BillingService
的构造函数表明,我们希望通过PaypalCreditCardProcessor
和DatabaseTransactionLog
来构造这个对象。
PaypalCreditCardProcessor
和DatabaseTransactionLog
本身都是接口,但在依赖注入时需要注入的是它们的实现。Guice通过bindings
来绑定接口和对应的实现,具体绑定的逻辑可以通过继承AbstractModule
类来实现:
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);
}
}
上述代码中实现的modules就是Guice中的对象依赖图构造器(object-graph builder),在使用时我们将构造器传入Injector
对象中来构造BillingService
对象。在构造BillingService
对象的过程中,我们通过Guice构建了一个小型的对象依赖关系图,其中包含了BillingService
对象和它的两个依赖对象PaypalCreditCardProcessor
和DatabaseTransactionLog
。
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);
...
}
1. 译者认为,object graph
翻译为对象依赖关系图更能表明其含义。 ↩