Using Google Guice to inject java properties

前端 未结 5 1034
灰色年华
灰色年华 2021-02-02 14:24

I want to use google guice to make properties available in all classes of my application. I defined a Module which loads and binds the properties file Test.properties.<

5条回答
  •  说谎
    说谎 (楼主)
    2021-02-02 14:41

    guice-config


    Usage example: At first we have a properties file 'config.properties':

    test.key=test value
    

    And we want to inject this value like this:

    @Inject
    @Config( Property.TEST_KEY )
    private String injectedValue;
    

    We need to load contents of file 'config.properties' into java.util.Properties and pass it to Config module:

    Properties props = new Properties();
    props.load(...);
    

    Module configModule = new ConfigModule( props, Property.values() ); ... and injecting:

    Injector injector = Guice.createInjector( configModule );
    TestClass testClass = injector.getInstance( TestClass.class );
    String injectedValue = testClass.getInjectedValue();
    

    injected value will be 'test value'...

提交回复
热议问题