guice注射器使用的最佳实践

时间:2018-06-08 09:19:09

标签: java dependency-injection guice

来自Guice文档:

 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的实例 - 我需要保持关于注入器变量的链接来执行此操作吗?

我的意思是,在其他课程中,我需要做这样的事情:

BillingService billingService = MainClass.injector.getInstance(BillingService.class)

获取BillingService的实例?这对我来说似乎并不优雅,有没有其他方法可以做到这一点?

1 个答案:

答案 0 :(得分:3)

这就是模块存在的原因。

只需在createInjector(...)方法中添加几个模块即可。

如果通过模块引用了其他类,则只需编写以下内容:

class PaymentService {
  @Inject BillingService billingService;
}

我要做的是使用“应用程序”类开始一切,就像你有main方法一样,只是在Guice配置的类中。