Search code examples
javaplayframeworkguice

Accessing application.conf on play module configuration


I'm trying to configure a database client instance using Guice to create an AbstractModule, but i can't access application.conf using dependency injection, since the injector is not created yet.

Here is my code

@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);
    }
}

How can i access the configuration without using the deprecated Play.configuration API?


Solution

  • You can pass it in the constructor (in Scala). Here is the example from my project

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

    In Java it is the same:

    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;
      }
    
      ...
    
    }
    

    More details: https://www.playframework.com/documentation/2.6.x/JavaDependencyInjection#Configurable-bindings

    Just do not overuse it:

    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.

    I very very rarely use it. It is always almost better to inject the configuration into component itself.