Skip to content

Instantly share code, notes, and snippets.

@573
Forked from stantonk/TestPropertiesInjection.java
Last active August 29, 2015 14:14
Show Gist options
  • Save 573/acc15d26314a9e4e1e07 to your computer and use it in GitHub Desktop.
Save 573/acc15d26314a9e4e1e07 to your computer and use it in GitHub Desktop.
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.google.inject.name.Names;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class TestPropertiesInjection {
private final String myprop;
@Inject
public TestPropertiesInjection(@Named("myprop") String myprop) {
this.myprop = myprop;
}
public String getMyprop() {
return myprop;
}
public static void main(String[] args) {
AbstractModule module = new AbstractModule() {
@Override
protected void configure() {
Properties defaults = new Properties();
defaults.setProperty("myprop", "default");
try {
Properties props = new Properties(defaults);
props.load(new FileInputStream("my.properties"));
Names.bindProperties(binder(), props);
} catch (IOException e) {
logger.error("Could not load config: ", e);
System.exit(1);
}
}
};
final TestPropertiesInjection instance = Guice.createInjector(module).getInstance(TestPropertiesInjection.class);
System.out.println("myprop = " + instance.getMyprop());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment