Guice and properties files

benstpierre picture benstpierre · Jun 18, 2010 · Viewed 18.3k times · Source

Does anybody have an example of how to use Google Guice to inject properties from a .properties file. I was told Guice was able to validate that all needed properties exist when the injector starts up.

At this time I cannot find anything on the guice wiki about this.

Answer

ColinD picture ColinD · Jun 18, 2010

You can bind properties using Names.bindProperties(binder(), getProperties()), where getProperties returns a Properties object or a Map<String, String> (reading the properties file as a Properties object is up to you).

You can then inject them by name using @Named. If you had a properties file:

foo=bar
baz=true

You could inject the values of those properties anywhere you wanted, like this:

@Inject
public SomeClass(@Named("foo") String foo, @Named("baz") boolean baz) {...}

Guice can convert values from strings to the type being injected, such as the boolean above, automatically (assuming the string is an appropriate format). This works for primitive types, enums and class literals.