43

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.

benstpierre
  • 32,833
  • 51
  • 177
  • 288

1 Answers1

73

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.

ColinD
  • 108,630
  • 30
  • 201
  • 202
  • NB, using guice 3.0-rc2 (current latest version), this only works if you import @Named from the guice.* packages, not javax.inject.Named. – Matthew Gilliard Feb 19 '11 at 14:52
  • @mjg123: That should not be true... I implemented the feature that makes Guice `@Named` and `@javax.inject.Named` interchangeable myself. See the test [here](http://code.google.com/p/google-guice/source/browse/trunk/core/test/com/google/inject/name/NamedEquivalanceTest.java), which includes a test that this works with `Names.bindProperties`. Have you tried it? – ColinD Feb 19 '11 at 15:05
  • 1
    Yes I did try it - I was looking at this page because I had the same question as the OP. I found that specifically for the case of `boolean` injection, it *did* matter which I used, although I admit I'm far from an expert in Guice. – Matthew Gilliard Mar 02 '11 at 20:02
  • @mjg123: I just tried it again myself using `@javax.inject.Named` and the example above (with `bindProperties`) and everything worked fine. If there is some situation where you're having to use the Guice `@Named`, could you make a small test that exposes that and report it [here](http://code.google.com/p/google-guice/issues/entry)? – ColinD Mar 02 '11 at 20:40
  • sure, if I can reproduce it I'll post a new question. – Matthew Gilliard Mar 02 '11 at 20:46