Guice and general application configuration

前端 未结 4 1756
时光说笑
时光说笑 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:29

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

提交回复
热议问题