Last active
August 9, 2018 17:55
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
Is there an example of what the properties file would look like?