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.
Guice is an open source, Java-based dependency injection framework. It is quiet lightweight and is actively developed/managed by Google.
Guice comes with a built-in binding annotation @Named that takes a string: public class RealBillingService implements BillingService { @Inject public RealBillingService(@Named("Checkout") CreditCardProcessor processor, TransactionLog transactionLog) { ... }
Guice figures out how to give you an Emailer based on the type. If it's a simple object, it'll instantiate it and pass it in. If it has dependencies, it will resolve those dependencies, pass them into it's constructor, then pass the resulting object into your object.
Google Guice (pronounced like "juice") is an open-source software framework for the Java platform released by Google under the Apache License. It provides support for dependency injection using annotations to configure Java objects.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With