Google Guice, addiction injector
The purpose of a dependency injector is to have access to objects, without worrying about their instantiation. How and when to instantiate them? How to refer to them? These are problems that Google Guice will be able to answer for you.
Three steps are important for its use:
- Declare its listener (application entry point) in web.xml which extends GuiceServletContextListener
- Declare your dependencies in the listener via modules
- Access your dependencies from anywhere with a simple injection annotation (in your constructors, methods, properties, ...)
In Guice, a dependency can be :
- A class (a "singleton" service)
- An instance of a class
- A constant
- A Provider (this can be thought of as a context-dependent object getter at the time it is called, like a session object)
One of the advantages of declaring dependencies (services and others) in Java rather than in XML (Spring) is to control what is injected according to the execution context. Typically :
- For unit tests, easily start the service(s) under test only
- Also for unit tests, injecting another instance to a dependency, with a mock or a lighter implementation of a service
- For your different environments (integration / production and customer / supplier), mock up third party applications very easily
- For your modular projects, no matter what is injected and where it is done, simply access your dependency
Guice also allows you to declare the filters and Web Services of your webapp in Java. There too, the interest is to be able to freely manipulate your declarations.
Finally, another good reason to adopt this framework: Its editor 🙂 It is also known for its light, reliable and efficient developments!
Some examples of use:
1. Declaration of dependencies in a "Module
2. Declaration of Modules
3. Use of Jersey in Guice (JAX-RS implementation (JSR 311) for RESTful WebServices)
3.1 List of webServices in an "Application" object
3.2 Declaration of WebServices in a ServletModule
Are you interested in this topic?