title: Using Google Guice to inject java properties
body: <p>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 <em>Test.properties</em>.</p>
  
  <pre><code>Property1=TEST
  Property2=25
  </code></pre>
  
  <p>package com.test;</p>
  
  <pre><code>import java.io.FileNotFoundException;
  import java.io.FileReader;
  import java.io.IOException;
  import java.util.Properties;
  
  import com.google.inject.AbstractModule;
  import com.google.inject.name.Names;
  
  public class TestConfiguration extends AbstractModule {
  
      @Override
      protected void configure() {
      Properties properties = new Properties();
      try {
          properties.load(new FileReader("Test.properties"));
          Names.bindProperties(binder(), properties);
      } catch (FileNotFoundException e) {
          System.out.println("The configuration file Test.properties can not be found");
      } catch (IOException e) {
          System.out.println("I/O Exception during loading configuration");
      }
  
      }
  }
  </code></pre>
  
  <p>I'm using a main class where I create a injector to inject the properties.</p>
  
  <pre><code>package com.test;
  
  import com.google.inject.Guice;
  import com.google.inject.Injector;
  
  public class Test {
  
      public static void main(String[] args) {
      TestConfiguration config = new TestConfiguration();
      Injector injector = Guice.createInjector(config);
      TestImpl test = injector.getInstance(TestImpl.class);
      }
  }
  
  package com.test;
  
  import com.google.inject.Inject;
  import com.google.inject.name.Named;
  
  public class TestImpl {
      private final String property1;
      private final Integer property2;
  
          @Inject
          public TestImpl(@Named("Property1") String property1, @Named("Property2") Integer property2) {
  
          System.out.println("Hello World");
          this.property1 = property1;
          this.property2 = property2;
  
          System.out.println(property1);
          System.out.println(property2);
  
          }
       }
  </code></pre>
  
  <p>Now my question. If my TestImpl creates other classes where I also need to inject properties, and those classes also need to inject properties what is the correct way to do this?</p>
  
  <ol>
  <li><p>Pass the injector to all subclasses and then use injector.getInstance(...) to create the subclasses?</p></li>
  <li><p>Instanciate a new injector like</p>
  
  <pre><code>TestConfiguration config = new TestConfiguration();
  Injector injector = Guice.createInjector(config);
  TestImpl test = injector.getInstance(TestImpl.class);
  </code></pre></li>
  </ol>
  
  <p>in all nested classes?</p>
  
  <ol>
  <li>Is there an other approach to make the properties available in all classes? </li>
  </ol>