Guice and general application configuration

丶灬走出姿态 提交于 2019-12-03 00:09:25

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

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

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");
            }
    });    
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!