Friday, May 1, 2015

Google DI Guice - @ImplementedBy

The content below is taken from here:
http://blog.decaresystems.ie/2007/06/14/juicy-code-with-google-guice-part-4/
All parts about GUICE from the same source:
Part 2 – First Code
Part 3 – Dependency Injection
Part 4 – @ImplementedBy and Annotating Bindings
Part 5 – Custom Providers and Conclusions
As I mentioned in the previous blog entries, you configure Google Guice by creating a class that implements the Module interface or better, one that extends AbstractModule class. In this class you specify the bindings that logically connects implementations to interfaces. However, there’s a way that lets you create the bindings using annotations without needing to write the code in a Module implementation. You can do that using the@ImplementedBy annotation decorating an interface.
Let’s see a quick example:
1
2
3
4
5
6
7
8
import com.google.inject.ImplementedBy;
@ImplementedBy(MobilePhone.class)
public interface Phone {
public void ring();
}
The simple interface above is decorated with the @ImplementedBy annotation and the name of the implementer is specified as a single attribute.
1
2
3
4
5
6
7
public class MobilePhone implements Phone {
public void ring() {
System.out.println("It's playing some annoying melody...");
}
}