At tonight's Cincinnati Java User Group meeting, Adam Schaible gave a presentation on Guice (pronounced 'juice') which is lightweight Java dependency injection framework from Google. He first gave a short introduction to dependency injection, with reference to the classic Martin Fowler example about a mythical MovieFinder class, but quickly moved on to looking at code. Compared to other dependency injection frameworks I've seen, the feature that quickly differentiates Guice is that it is configured completely in code and annotations and not in XML. One major advantage of this is that it leverages strong typing, both for compile time checking of class names and refactoring support. The primary disadvantage is that you must recompile the code to make configuration changes.
The great thing abut Guice is that it makes the easy things easy. For example, it is common to have one default production implementation for an interface. You can express this quite easily in Guice with an annotation on the interface definition:
@ImplementedBy(ServiceImpl.class)
public interface Service {
void go();
}
This code snippet sets the ServiceImpl as the default class to be created when an instance of Service is requested, no other configuration necessary.
Adam described the key components of Guice as:
- Modules
- Injectors
- Providers
- Automated Bindings
- Scope
Injectors create objects. Modules provide configuration regarding which classes to create for a given interface; injectors can be created with a list of modules. Providers can be used to customize object creation; the Guice User's Guide has an example of a custom provider for integrating with JNDI. I don't remember Adam talking about automated bindings, but I think he may have been referring to the ImplementedBy annotation described above, which creates an automatic binding between the Service interface and ServiceImpl class. Last is scope. By default, Guice creates a new object for every injection. Using scope you can change that behavior. For example, you could use singleton to ensure the same instance is returned for each injection.
Some other features of Guice include easy handling of development stages (development, QA, production), the ability to intercept methods, and easily create objects via either eager or lazy loading. Guice is also lightweight; for basic operation it requires a single jar file of approximately 500k.
There was a lot of discussion and questions from the twenty four attendees. Many people were obviously using Spring and there were many questions comparing Spring to Guice or asking how to use Guice with Spring.
Ascendum Solutions provided the pizza for the meeting and announced a networking event to be held February 27 from 6:00-8:00 PM at Buffalo Wild Wings in Glendale. The next Java user group meeting will cover the web framework Wicket.
0 comments: (+add yours?)
Post a Comment