访问 application.conf 播放模块配置

Accessing application.conf on play module configuration

我正在尝试使用 Guice 配置数据库客户端实例以创建 AbstractModule,但我无法使用依赖注入访问 application.conf,因为尚未创建注入器。

这是我的代码

@Singleton
public class DatastoreModule extends AbstractModule {

    @Inject
    private Config config;

    @Override
    public void configure() {

        MongoClient mongo = new MongoClient(
                config.getString("mongodb.host"),
                config.getInt("mongodb.port")
        );

        Morphia morphia = new Morphia();

        Datastore datastore = morphia.createDatastore(
                mongo,
                config.getString("mongodb.databaseName")
        );

        bind(Datastore.class).toInstance(datastore);
    }
}

如何在不使用已弃用的 Play.configuration API 的情况下访问配置?

您可以在构造函数中传递它(在 Scala 中)。这是我项目中的例子

class Guard(environment: Environment, configuration: Configuration) extends AbstractModule{

在Java中是一样的:

public class DatastoreModule extends AbstractModule {

  private final Environment environment;
  private final Config config;

  public DatastoreModule(Environment environment, Config config) {
    this.environment = environment;
    this.config = config;
  }

  ...

}

更多详情:https://www.playframework.com/documentation/2.6.x/JavaDependencyInjection#Configurable-bindings

只是不要过度使用它:

In most cases, if you need to access Config when you create a component, you should inject the Config object into the component itself or into the component’s Provider. Then you can read the Config when you create the component. You usually don’t need to read Config when you create the bindings for the component.

我很少使用它。将配置注入组件本身几乎总是更好。