javaconfigurationguiceapache-commons-config

Guice and general application configuration


For a monitoring software written in Java I consider using Google Guice as DI provider. The project needs to load its configuration from an external resource (file or database). The application is designed to run in standalone mode or in a servlet container.

At the moment the configuration does not contain bindings or parameters for dependency injection, only some global application settings (JDBC connection definitions and associated database management/monitoring objects).

I see two options:

or

Would you recommend to use Guice for both tasks, or keep the general application configuration separate from the dependency injection? Which advantages and disadvantages would you consider the most important ones?


Solution

  • It's straightforward to slurp a property file in a Guice module:

    public class MyModule extends AbstractModule {
    
      @Override
      protected void configure() {
        try {
            Properties properties = new Properties();
            properties.load(new FileReader("my.properties"));
            Names.bindProperties(binder(), properties);
        } catch (IOException ex) {
            //...
        }
      }
    } 
    

    Later it's easy to switch from Properties to other config sources.

    [Edit]

    BTW, you can get the injected properties by annotating it with @Named("myKey").