Guice and properties files

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.

Leave a Comment