As promised in the previous article I’ll continue presenting Google Guice also for web applications. In order to do this you’ll need to get the servlet extension – part of the standard distribution, along with other extensions like JMX, JNDI, Persist, Struts or Spring. Using Guice, the web.xml will be reduced at minimum – just make the Guice container start. The rest of the configurations will be easily done in Java in the same type-safe manner presented in the previous article.
The servlets will benefit from:
What is Guice?
To quote from the Guice official page
“Guice alleviates the need for factories and the use of new in your Java code. Think of Guice’s @Inject as the new new. Guice embraces Java’s type safe nature, especially when it comes to features introduced in Java 5 such as generics and annotations. You might think of Guice as filling in missing features for core Java. Ideally, the language itself would provide most of the same features, but until such a language comes along, we have Guice”
If you’ve used Spring or other DI frameworks you’re probably familiar to the above ideas. I’ll present in this article how to get started with Guice in a non-web application. I’ll detail the web side in a future article.
Is it better than Spring?
Well, this is one of those talks that could last forever. Like EJB vs Spring, Struts vs JSF and so on. It’s a matter of choice. I can say one thing though: if you need just DI in your application go for Guice. It’s very lightweight, it’s type safe and it’s faster than Spring.
Using Guice for a non-web application
Suppose you have an application and the class that contains the main method its called Application. When using Guice the approach is a little changed. Besides starting the application you’ll also want a way to trigger the dependency injection. In order to to this you must have an “entry-point” that “manually” triggers the creation of the graph of objects that will get injected and only after that starts the actual application logic. We’ll call the class responsible for these 2 things the Bootstrap class. We also need to create a Module by extending the AbstractModule class. Quoting from the Java Doc of the Module interface:
A module contributes configuration information, typically interface bindings, which will be used to create an
Injector. A Guice-based application is ultimately composed of little more than a set of
Modules and some bootstrapping code.
Let’s see the code:
The Bootstrap class:
Continue reading “Guice – a lightweight DI framework alternative to Spring”