Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guice and properties files

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.

like image 529
benstpierre Avatar asked Jun 18 '10 17:06

benstpierre


People also ask

Does Google use Guice?

Guice is an open source, Java-based dependency injection framework. It is quiet lightweight and is actively developed/managed by Google.

What is @named annotation in Guice?

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) { ... }

How does Guice dependency injection work?

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.

What is Guice used for?

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.


1 Answers

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.

like image 133
ColinD Avatar answered Sep 28 '22 02:09

ColinD