I've read about Google Guice, and understand the general issues with other approaches to dependency injection, however I haven't yet seen an example of someone using Guice "in practice" where its value becomes clear.
I'm wondering if anyone is aware of any such examples?
Using Google Guice to provides ease in unit testing is only high-level advantage. Some people might not even use unit testing in their project. People has been using Spring/Dependency Injection more than only for unit testing.
The low level advantage of using Google Guice is a matter of cohesion in your application, your classes in the project can be loosely coupled between each other. I can provide a class for another class without them being dependent to each other.
Consider this example:
public class A {
}
public class B {
A a = new A();
}
Class B would be tightly coupled to Class A, or in other words it is dependent to class A's existence.
But with Guice I can instead make it loosely coupled like this:
public class B {
private A a;
@Inject
public B(A a) {
this.a = a;
}
}
Class B
is now loosely coupled to A
, and Guice is responsible to provide the instance of A
instead of B
having to instantiate it. With this you can extend it to provide interface of A
to B
, and the implementation can be a Mock object if you want to unit test your apps.
Having said that we're only discussing the benefits of Dependency Injection so far. Beyond Dependency Injection, the benefits of using Google Guice is:
@Inject
annotation constructor.That's the overview of it. But as you get deeper with Guice, there's so many more good things about it. A simple real life example is if you are using GWT with MVP implementation, the components/widgets in your GWT application are very loosely coupled and not tightly integrated to each other.