Skip to content

Instantly share code, notes, and snippets.

@stantonk
Last active August 9, 2018 17:55
Show Gist options
  • Save stantonk/8e37cd97da1c0c800d27 to your computer and use it in GitHub Desktop.
Save stantonk/8e37cd97da1c0c800d27 to your computer and use it in GitHub Desktop.
Example of loading a Java properties file and binding to @nAmed attributes in Guice. Handles default property settings as well. Adapted from code written by https://github.com/kylemcc
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());
}
}
@JSumm3990
Copy link

Is there an example of what the properties file would look like?

@Soontao
Copy link

Soontao commented Aug 24, 2017

it works

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment