2. Agenda
• Dependency Injection? YES/NO
• Google Guice Introduction
• Google Guice : HOW?
• Module
• Binding
• Scope
• Injection (Constructor, Field, and Method)
• Graph
• Demo
• Q & A
3. 3
Dependency Injection
class SAMSUNG_S3() {
SAMSUNG_S3() {
ISpeaker s = new Speaker();
IMicro m = new Micro();
IScreen s = new Screen();
IKeyboard k = new Keyboard();
...
IHardDrive hd = new HardDrive();
IGraphicMemory gm = new GraphicMemory();
IGraphicCard g = new GraphicCard(gm);
ICPU c = new CPU();
//And finally!!!
samsungS3 = new Phone(s,m,g, c,…, ... ); }
}
Spagetti Code
4. 4
Dependency Injection
class IPhone() {
IPhone() {
ISpeaker s = new Speaker();
IMicro m = new Micro();
IScreen s = new Screen();
IKeyboard k = new Keyboard();
...
IHardDrive hd = new HardDrive();
IGraphicMemory gm = new GraphicMemory();
IGraphicCard g = new GraphicCard(gm);
ICPU c = new CPU();
//And finally!!!
iphone = new Phone(s,m,g, c,…, ... ); }
}
How many “new” in your application?
Wild Programmer
6. 6
Google Guice
• Guice is a dependency injection framework, which
alleviates the need for factories and use of new in your
java code.
• Google Guice implements the JSR-330
• Above Java 5 and brought to you by Google.
7. 7
Google Guice
• Guice Module
• Binding
• Scope
• Injection (Constructor, Field, and Method)
• Graph
9. 9
Binding Types
• Multi Binding:
public class RequestLifecycleBinder1 extends AbstractModule {
@Override
protected void configure() {
Multibinder<ComponentRequestLifecycle> multibinder = Multibinder.newSetBinder(binder(), ComponentRequestLifecycle.class);
multibinder.addBinding().to(DBRequestLifecycle.class);
multibinder.addBinding().to(NoSQLRequestLifecycle.class);
}
}
class RequestLifecycleStack extends LinkedList<RequestLifecycle> {
@Inject
private Set<ComponentRequestLifecycle> allComponents;
10. 10
Scope
• Unscoped: one per use
• create it, use it, and destroy it.
• Singleton: one per application
• For heavyweight resources
• and application state.
11. 11
Scope
• Multi Binding
public class RequestLifecycleBinder1 extends AbstractModule {
@Override
protected void configure() {
Multibinder<ComponentRequestLifecycle> multibinder = Multibinder.newSetBinder(binder(), ComponentRequestLifecycle.class);
multibinder.addBinding().to(DBRequestLifecycle.class);
multibinder.addBinding().to(NoSQLRequestLifecycle.class);
}
}
class RequestLifecycleStack extends LinkedList<RequestLifecycle> {
@Inject
private Set<ComponentRequestLifecycle> allComponents;
12. 12
Demo
• Step 0: Using ‘new’ in order to create the
RewardApp
• Step 1: Creates Module and Binding
• A module is a collection of bindings which is passed to Injector on its creation
• Step 2: Multi Binding
• Step 3: Binding with annotation and Singleton
scope
• Step 4: JsonModule and Binding from Json