Guice:在特定条件下回退到默认实现

Guice: Fallback to default implementation on a particular condition

我是 guice 的新手。

我有一个文件(json 文件),我在其中定义了一些数据。这是可选的。如果文件存在,我必须从文件中读取数据(使用 FileBasedImpl)。否则,我应该从 "DefaultImpl" class 获取数据,其中我 return 是硬编码数据。

如何通过 guice 绑定实现这一点?

interface SomeService {
  Map<String, String> getData();
}

class FileBasedImpl implements SomeService {
   /* Reads from a file */
   Map<String, String> getData() {
      //Check if file is present, then read the data
   }
}

class DefaultImpl implements SomeService {
  /* Returns hard-coded data */
  Map<String, String> getData() {
    return new HashMap()<>..;
  }
}

您可以创建一个提供程序(通过实现接口或向您的模块添加提供方法)来尝试读取内容并根据结果提供一个或另一个 bean:

...
@Provides
public SomeService someService() {
    File file = ....;
    return (file.exists) ? new FileBasedImpl(file) : new DefaultImpl();
}
...

不过要小心,模块中的条件逻辑是 documented anti-pattern。但在这种情况下,这是一个很好且有效的解决方案,但有时必须这样做......