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).
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")
.
Check the governator library:
https://github.com/Netflix/governator/wiki/Configuration-Mapping
You will get a @Configuration annotation and several configuration providers. In code it helps to see where is You configuration parameters used:
@Configuration("configs.qty.things")
private int numberOfThings = 10;
Also, You will get a nice configuration report on startup:
https://github.com/Netflix/governator/wiki/Configuration-Mapping#configuration-documentation
I ran into the same problem in my own project. We had already chosen Guice as DI-framework and to keep things simple wanted to use it also with configuration.
We ended up reading the configuration from properties file using Apache Commons Configuration and binding them to Guice injector like suggested in Guice FAQ How do I inject configuration parameters?.
@Override public void configure() {
bindConstant().annotatedWith(ConfigurationAnnotation.class)
.to(configuration.getString("configurationValue"));
}
Reloading of configuration supported by Commons Configuration is also quite easy implement into Guice injection.
@Override public void configure() {
bind(String.class).annotatedWith(ConfigurationAnnotation.class)
.toProvider(new Provider<String>() {
public String get() {
return configuration.getString("configurationValue");
}
});
}
Try Guice configuration available on maven central, it's support Properties, HOCON and JSON format.
You can inject properties from file application.conf to your service as :
@BindConfig(value = "application")
public class Service {
@InjectConfig
private int port;
@InjectConfig
private String url;
@InjectConfig
private Optional<Integer> timeout;
@InjectConfig("services")
private ServiceConfiguration services;
}
You must install the modules ConfigurationModule as
public class GuiceModule extends AbstractModule {
@Override
protected void configure() {
install(ConfigurationModule.create());
requestInjection(Service.class);
}
}