Guice and general application configuration

mjn picture mjn · Jan 26, 2011 · Viewed 21k times · Source

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

  • to use a file based addon for Guice like guice-xml-config to store the application options (this would allow to configure the DI part later if it becomes necessary).

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?

Answer

Landei picture Landei · Jan 26, 2011

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").