SlideShare ist ein Scribd-Unternehmen logo
1 von 15
Google Guice
Dependency Injection
VŨ CÔNG THÀNH
Tech Core team
Agenda
• Dependency Injection? YES/NO
• Google Guice Introduction
• Google Guice : HOW?
• Module
• Binding
• Scope
• Injection (Constructor, Field, and Method)
• Graph
• Demo
• Q & A
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
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
5
Dependency Injection
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
Google Guice
• Guice Module
• Binding
• Scope
• Injection (Constructor, Field, and Method)
• Graph
8
Guice Module
• Binding: Interface -> Implementation
public class RDBMSRewardBinder extends AbstractModule {
@Override
protected void configure() {
//Advertiser
bind(AdvertisersService.class).to(AdvertisersServiceImpl.class);
bind(AdvertisersStorage.class).to(AdvertisersJPAImpl.class);
bind(AdvertiserUsersService.class).to(AdvertiserUsersServiceImpl.class);
bind(AdvertiserUsersStorage.class).to(AdvertiserUsersJPAImpl.class);
//user
bind(UsersService.class).to(UsersServiceImpl.class);
bind(UserDevicesService.class).to(UserDevicesServiceImpl.class);
bind(UsersStorage.class).to(UsersJPAImpl.class);
bind(UserDevicesStorage.class).to(UserDevicesJPAImpl.class);
bind(UserStatusLogsStorage.class).to(UserStatusLogsJPAImpl.class);
bind(UserRefreshTokenService.class).to(UserRefreshTokenServiceImpl.class);
bind(UserRefreshTokensStorage.class).to(UserRefreshTokensJPAImpl.class);
...
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
Scope
• Unscoped: one per use
• create it, use it, and destroy it.
• Singleton: one per application
• For heavyweight resources
• and application state.
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
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
13
Demo
• Step 5: Graph Objects
14
References
• Source Code:
• https://github.com/thanhvc/guice-demo
• https://github.com/google/guice/wiki/GettingStart
ed
Q&A

Weitere ähnliche Inhalte

Andere mochten auch

Children young people and the arts_Arts Council England South West
Children young people and the arts_Arts Council England South WestChildren young people and the arts_Arts Council England South West
Children young people and the arts_Arts Council England South WestMartin Thomas
 
도박의세계『SX797』『СOM』카지노싸이트
도박의세계『SX797』『СOM』카지노싸이트도박의세계『SX797』『СOM』카지노싸이트
도박의세계『SX797』『СOM』카지노싸이트hdlkfjgldf
 
Katja Rajala liikuntatieteenpäivät 2015
Katja Rajala liikuntatieteenpäivät 2015Katja Rajala liikuntatieteenpäivät 2015
Katja Rajala liikuntatieteenpäivät 2015LIKESresearchcenter
 
Собрать нельзя клонировать. Как выбрать подход к созданию кроссплатформенных ...
Собрать нельзя клонировать. Как выбрать подход к созданию кроссплатформенных ...Собрать нельзя клонировать. Как выбрать подход к созданию кроссплатформенных ...
Собрать нельзя клонировать. Как выбрать подход к созданию кроссплатформенных ...Ilya Slobodin
 
GLORY BEACH PACKAGES 2016
GLORY BEACH PACKAGES 2016GLORY BEACH PACKAGES 2016
GLORY BEACH PACKAGES 2016Jeevan Barath
 

Andere mochten auch (8)

Children young people and the arts_Arts Council England South West
Children young people and the arts_Arts Council England South WestChildren young people and the arts_Arts Council England South West
Children young people and the arts_Arts Council England South West
 
Final
FinalFinal
Final
 
M2 t1 planificador_aamtic.docx
M2 t1 planificador_aamtic.docxM2 t1 planificador_aamtic.docx
M2 t1 planificador_aamtic.docx
 
도박의세계『SX797』『СOM』카지노싸이트
도박의세계『SX797』『СOM』카지노싸이트도박의세계『SX797』『СOM』카지노싸이트
도박의세계『SX797』『СOM』카지노싸이트
 
ملخص البرمجة المرئية - الوحدة السادسة
ملخص البرمجة المرئية - الوحدة السادسةملخص البرمجة المرئية - الوحدة السادسة
ملخص البرمجة المرئية - الوحدة السادسة
 
Katja Rajala liikuntatieteenpäivät 2015
Katja Rajala liikuntatieteenpäivät 2015Katja Rajala liikuntatieteenpäivät 2015
Katja Rajala liikuntatieteenpäivät 2015
 
Собрать нельзя клонировать. Как выбрать подход к созданию кроссплатформенных ...
Собрать нельзя клонировать. Как выбрать подход к созданию кроссплатформенных ...Собрать нельзя клонировать. Как выбрать подход к созданию кроссплатформенных ...
Собрать нельзя клонировать. Как выбрать подход к созданию кроссплатформенных ...
 
GLORY BEACH PACKAGES 2016
GLORY BEACH PACKAGES 2016GLORY BEACH PACKAGES 2016
GLORY BEACH PACKAGES 2016
 

Ähnlich wie Eway google-guice presentation

Cocoa Heads Tricity - Design Patterns
Cocoa Heads Tricity - Design PatternsCocoa Heads Tricity - Design Patterns
Cocoa Heads Tricity - Design PatternsMaciej Burda
 
Easy path to machine learning
Easy path to machine learningEasy path to machine learning
Easy path to machine learningwesley chun
 
GEE Juli 2023.pptx
GEE Juli 2023.pptxGEE Juli 2023.pptx
GEE Juli 2023.pptxduabelaspkwu
 
Gg Code Mash2009 20090106
Gg Code Mash2009 20090106Gg Code Mash2009 20090106
Gg Code Mash2009 20090106Jim Shingler
 
DIとトレイとによるAndroid開発の効率化
DIとトレイとによるAndroid開発の効率化DIとトレイとによるAndroid開発の効率化
DIとトレイとによるAndroid開発の効率化Tomoharu ASAMI
 
GR8Conf 2009: Industrial Strength Groovy by Paul King
GR8Conf 2009: Industrial Strength Groovy by Paul KingGR8Conf 2009: Industrial Strength Groovy by Paul King
GR8Conf 2009: Industrial Strength Groovy by Paul KingGR8Conf
 
How To Build a Multi-Field Search Page For Your XPages Application
How To Build a Multi-Field Search Page For Your XPages ApplicationHow To Build a Multi-Field Search Page For Your XPages Application
How To Build a Multi-Field Search Page For Your XPages ApplicationMichael McGarel
 
SimpleModelerによるAndroidアプリ自動生成 with g3/g4
SimpleModelerによるAndroidアプリ自動生成 with g3/g4SimpleModelerによるAndroidアプリ自動生成 with g3/g4
SimpleModelerによるAndroidアプリ自動生成 with g3/g4Tomoharu ASAMI
 
Exploring Google (Cloud) APIs with Python & JavaScript
Exploring Google (Cloud) APIs with Python & JavaScriptExploring Google (Cloud) APIs with Python & JavaScript
Exploring Google (Cloud) APIs with Python & JavaScriptwesley chun
 
Java onguice20070426
Java onguice20070426Java onguice20070426
Java onguice20070426Ratul Ray
 
Introduction to Gradio library in python.pptx
Introduction to Gradio library in python.pptxIntroduction to Gradio library in python.pptx
Introduction to Gradio library in python.pptxvahid67ebrahimian
 
Design Patterns para Microsserviços com MicroProfile
 Design Patterns para Microsserviços com MicroProfile Design Patterns para Microsserviços com MicroProfile
Design Patterns para Microsserviços com MicroProfileVíctor Leonel Orozco López
 
Up and Running with Angular
Up and Running with AngularUp and Running with Angular
Up and Running with AngularJustin James
 
Introduction to Grunt.js on Taiwan JavaScript Conference
Introduction to Grunt.js on Taiwan JavaScript ConferenceIntroduction to Grunt.js on Taiwan JavaScript Conference
Introduction to Grunt.js on Taiwan JavaScript ConferenceBo-Yi Wu
 
Grails & Angular: unleashing the dynamic duo
Grails & Angular: unleashing the dynamic duoGrails & Angular: unleashing the dynamic duo
Grails & Angular: unleashing the dynamic duoRubén Mondéjar Andreu
 

Ähnlich wie Eway google-guice presentation (20)

OpenGL L03-Utilities
OpenGL L03-UtilitiesOpenGL L03-Utilities
OpenGL L03-Utilities
 
guice-servlet
guice-servletguice-servlet
guice-servlet
 
Cocoa Heads Tricity - Design Patterns
Cocoa Heads Tricity - Design PatternsCocoa Heads Tricity - Design Patterns
Cocoa Heads Tricity - Design Patterns
 
Easy path to machine learning
Easy path to machine learningEasy path to machine learning
Easy path to machine learning
 
GEE Juli 2023.pptx
GEE Juli 2023.pptxGEE Juli 2023.pptx
GEE Juli 2023.pptx
 
Gg Code Mash2009 20090106
Gg Code Mash2009 20090106Gg Code Mash2009 20090106
Gg Code Mash2009 20090106
 
DIとトレイとによるAndroid開発の効率化
DIとトレイとによるAndroid開発の効率化DIとトレイとによるAndroid開発の効率化
DIとトレイとによるAndroid開発の効率化
 
GR8Conf 2009: Industrial Strength Groovy by Paul King
GR8Conf 2009: Industrial Strength Groovy by Paul KingGR8Conf 2009: Industrial Strength Groovy by Paul King
GR8Conf 2009: Industrial Strength Groovy by Paul King
 
How To Build a Multi-Field Search Page For Your XPages Application
How To Build a Multi-Field Search Page For Your XPages ApplicationHow To Build a Multi-Field Search Page For Your XPages Application
How To Build a Multi-Field Search Page For Your XPages Application
 
Why Grails?
Why Grails?Why Grails?
Why Grails?
 
Why Grails
Why GrailsWhy Grails
Why Grails
 
SimpleModelerによるAndroidアプリ自動生成 with g3/g4
SimpleModelerによるAndroidアプリ自動生成 with g3/g4SimpleModelerによるAndroidアプリ自動生成 with g3/g4
SimpleModelerによるAndroidアプリ自動生成 with g3/g4
 
Exploring Google (Cloud) APIs with Python & JavaScript
Exploring Google (Cloud) APIs with Python & JavaScriptExploring Google (Cloud) APIs with Python & JavaScript
Exploring Google (Cloud) APIs with Python & JavaScript
 
Java onguice20070426
Java onguice20070426Java onguice20070426
Java onguice20070426
 
Introduction to Gradio library in python.pptx
Introduction to Gradio library in python.pptxIntroduction to Gradio library in python.pptx
Introduction to Gradio library in python.pptx
 
Design Patterns para Microsserviços com MicroProfile
 Design Patterns para Microsserviços com MicroProfile Design Patterns para Microsserviços com MicroProfile
Design Patterns para Microsserviços com MicroProfile
 
Ashish resume
Ashish resumeAshish resume
Ashish resume
 
Up and Running with Angular
Up and Running with AngularUp and Running with Angular
Up and Running with Angular
 
Introduction to Grunt.js on Taiwan JavaScript Conference
Introduction to Grunt.js on Taiwan JavaScript ConferenceIntroduction to Grunt.js on Taiwan JavaScript Conference
Introduction to Grunt.js on Taiwan JavaScript Conference
 
Grails & Angular: unleashing the dynamic duo
Grails & Angular: unleashing the dynamic duoGrails & Angular: unleashing the dynamic duo
Grails & Angular: unleashing the dynamic duo
 

Kürzlich hochgeladen

CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...soniya singh
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfCionsystems
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendArshad QA
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsAndolasoft Inc
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 

Kürzlich hochgeladen (20)

CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
Russian Call Girls in Karol Bagh Aasnvi ➡️ 8264348440 💋📞 Independent Escort S...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Active Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdfActive Directory Penetration Testing, cionsystems.com.pdf
Active Directory Penetration Testing, cionsystems.com.pdf
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Test Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and BackendTest Automation Strategy for Frontend and Backend
Test Automation Strategy for Frontend and Backend
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
How To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.jsHow To Use Server-Side Rendering with Nuxt.js
How To Use Server-Side Rendering with Nuxt.js
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 

Eway google-guice presentation

  • 1. Google Guice Dependency Injection VŨ CÔNG THÀNH Tech Core team
  • 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
  • 8. 8 Guice Module • Binding: Interface -> Implementation public class RDBMSRewardBinder extends AbstractModule { @Override protected void configure() { //Advertiser bind(AdvertisersService.class).to(AdvertisersServiceImpl.class); bind(AdvertisersStorage.class).to(AdvertisersJPAImpl.class); bind(AdvertiserUsersService.class).to(AdvertiserUsersServiceImpl.class); bind(AdvertiserUsersStorage.class).to(AdvertiserUsersJPAImpl.class); //user bind(UsersService.class).to(UsersServiceImpl.class); bind(UserDevicesService.class).to(UserDevicesServiceImpl.class); bind(UsersStorage.class).to(UsersJPAImpl.class); bind(UserDevicesStorage.class).to(UserDevicesJPAImpl.class); bind(UserStatusLogsStorage.class).to(UserStatusLogsJPAImpl.class); bind(UserRefreshTokenService.class).to(UserRefreshTokenServiceImpl.class); bind(UserRefreshTokensStorage.class).to(UserRefreshTokensJPAImpl.class); ...
  • 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
  • 13. 13 Demo • Step 5: Graph Objects
  • 14. 14 References • Source Code: • https://github.com/thanhvc/guice-demo • https://github.com/google/guice/wiki/GettingStart ed
  • 15. Q&A