Guice and general application configuration

前端 未结 4 1774
时光说笑
时光说笑 2021-02-04 01:30

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

4条回答
  •  难免孤独
    2021-02-04 02:26

    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() {
                public String get() {
                    return configuration.getString("configurationValue");
                }
        });    
    }
    

提交回复
热议问题