java - 吉斯 IOC : Manual (and Optional) Creation of a Singleton

标签 java guice

尝试开始使用 Guice,并努力了解我的用例如何适合。

我有一个命令行应用程序,它需要几个可选参数。

例如,假设我有显示客户订单的工具

 order-tool display --customerId 123

这显示了 ID 为 123 的客户拥有的所有订单。现在,用户还可以指定用户名:

order-tool display --customerName "Bob Smith"

但是查询订单的接口(interface)依赖于客户 ID。因此,我们需要将客户名称映射到客户 ID。为此,我们需要连接到客户 API。因此,用户必须指定:

order-tool display --customerName "Bob Smith" --customerApi "http://localhost:8080/customer"

启动应用程序时,我想解析所有参数。在指定 --customerApi 的情况下,我想在我的 IoC 上下文中放置一个 CustomerApi 单例 - 它由 CLI arg 和 API URL 进行参数化。

然后,当代码运行以按名称显示客户时,它会询问上下文是否有 CustomerApi 单例。如果没有,它会抛出异常,告诉 CLI 用户如果想要使用 --customerName,则需要指定 --customerApi。但是,如果已经创建了一个 - 那么它只是从 IoC 上下文中检索它。

最佳答案

听起来“选择性地创建一个单例”并不完全是您在这里想要做的。我的意思是,确实如此,但这很简单:

if (args.hasCustomerApi()) {
  bind(CustomerApi.class).toInstance(new CustomerApi(args.getCustomerApi()));
}

要允许可选绑定(bind),您可能需要annotate their use with @Nullable .

我认为您真正的问题是如何构建应用程序,以便您可以部分配置它,使用配置来读取和验证一些命令行标志,然后使用这些标志来完成应用程序的配置。我认为最好的方法是使用子注入(inject)器。

public static void main(String[] args) {
  Injector injector = Guice.createInjector(new AModule(), new BModule(), ...);
  Arguments arguments = injector.getInstance(ArgParser.class).parse(args);
  validateArguments(arguments);  // throw if required arguments are missing
  Injector childInjector =
      injector.createChildInjector(new ArgsModule(arguments));
  childInjector.getInstance(Application.class).run();
}

Child injectors就像普通的注入(inject)器一样,如果它们本身不包含给定的绑定(bind),则它们会遵循父级。您还可以阅读how Guice resolves bindings上的文档.

关于java - 吉斯 IOC : Manual (and Optional) Creation of a Singleton,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20246165/

相关文章:

java - 这对 sftp : java or shell script? 更有效

scala - DI 或服务定位器 : Injecting implementations at run-time ( no static binding ) in scala

java - 为什么我们在发现 @Inject 方法时会遇到 StackOverflowError ?

java - 指定子类的注入(inject)

java - 如何包装 Google Guice 的 Injector 方法?

java - eclipse 赫利俄斯 : Java EE Perspective: How to have jars added to build path under one hood like referenced library

java - 在应用程序启动时从 java 清空字符设备

java - 为什么 JavaFX 中的最终类 WebView 包含 protected 方法 getChildren()?

java - try-with-resource 中的 close() 异常

java - 将 key 动态传递给@Named 注解