SlideShare a Scribd company logo
1 of 26
INTRODUCTION TO GOOGLE GUICE
Jyotsna Karan
Software Consultant
Knoldus Software LLP
AGENDA
lIntroduction to Dependency Injection
lWhat is Google Guice
lExploring the Guice API
lInjector
lModule
lGuice
lBinder
lThe ability to supply (inject) an external dependency into a
software component.
lTypes of Dependency Injection:
lConstructor injection
lSetter injection
lCake pattern
lGoogle-guice
What is Dependency Injection
Benefits of Dependency Injection
lSome of the benefits of using Dependency Injection are:
lSeparation of Concerns
lBoilerplate Code reduction in application classes because all
work to initialize dependencies is handled by the injector
component
lConfigurable components makes application easily extendable
lUnit testing is easy with mock objects
Disadvantages of Dependency Injection
lIf overused, it can lead to maintenance issues because effect of
changes are known at runtime.
lDependency injection hides the service class dependencies that
can lead to runtime errors that would have been caught at
compile time.
Exploring Google Guice
lGoogle Guice is a Dependency Injection Framework that can be
used by Applications where Relation-ship/Dependency between
Business Objects have to be maintained manually in the
Application code.
Trait Storage {
def store(data: Data)
def retrieve(): String
}
Exploring Google Guice
class FileStorage extends Storage {
def store(data: Data) = {
// Store the object in a file using Java Serialization mechanism.
}
def retrieve(): String = {
// Code to retrieve the object.
""
}
}
class StorageClient extends App {
// Making use of file storage.
val storage = new FileStorage();
storage.store(new Data());
}
A Simple Guice Example :
trait CreditCardProcessor {
def charge(): String
}
class CreditCardProcessorImpl extends CreditCardProcessor {
def charge(): String = {
//
}
}
trait BillingService {
def chargeOrder(order: PizzaOrder, creditCard: CreditCard): String
}
class RealBillingService @Inject() (processor: CreditCardProcessor) extends BillingService {
def chargeOrder(order: PizzaOrder, creditCard: CreditCard): String = {
//some code code process order
val result = processor.charge()
result
}
}
A Simple Guice Example (contd..):
class BillingModule extends Module {
def configure(binder: Binder) ={
binder.bind(classOf[CreditCardProcessor]).to(classOf[CreditCardProcessorImpl])
binder.bind(classOf[BillingService]).to(classOf[RealBillingService])
}
}
object GuiceApp extends App {
val module = new BillingModule
val injector = Guice.createInjector(module)
val component = injector.getInstance(classOf[BillingService])
println("Order Successful : " +
component.chargeOrder(PizzaOrder("garlicBread", 4), CreditCard()))
}
Injector
Injectors take care of creating and maintaining Objects that are used by
the Clients.
Injectors do maintain a set of Default Bindings from where they can
take the Configuration information of creating and maintaining Relation-
ship between Objects.
To get all the Bindings associated with the Injector, simply make a call
to Injector.getBindings() method which will return a Map of Binding
objects.
val injector = Guice.createInjector(new BillingModule)
val component = injector.getInstance(classOf[BillingService])
val bindings = injector.getBindings
Module
Module is represented by an interface with a method
called Module.configure() which should be overridden by the Application to
populate the Bindings.
To simplify things, there is a class called AbstractModule which directly
extends the Module interface. So Applications can depend
on AbstractModule rather than Module.
class BillingModule extends Module {
def configure(binder: Binder) = {
//code that binds the information using various flavours of bind
}
}
lGuice
Guice is a class which Clients directly depends upon to interact
with other Objects. The Relation-ship between Injector and the
various modules is established through this class.
For example consider the following code snippet,
val module = new BillingModule
val injector = Guice.createInjector(module)
Binder
This interface mainly consists of information related to Bindings. A
Binding refers a mapping for an Interface to its corresponding
Implementation.
For example, we refer that the interface BillingService is bound
to RealBillingService implementation.
binder.bind(classOf[BillingService]).to(classOf[RealBillingService])
Binder
To specify how dependencies are resolved, configure your injector with
bindings.
Creating Bindings
To create bindings, extend AbstractModule and override
its configure method.
In the method body, call bind() to specify each binding. These methods
are type checked so the compiler can report errors if you use the wrong
types.
Once you've created your modules, pass them as arguments
to Guice.createInjector() to build an injector.
lLinked Bindings
Linked bindings map a type to its implementation. This example maps
the interface CreditCardProcessor to the implementation
CreditCardProcessorImpl:
class BillingModule extends Module {
def configure(binder: Binder) ={
binder.bind(classOf[CreditCardProcessor]).to(classOf[CreditCardProcessorImpl])
}
}
binder.bind(classOf[CreditCardProcessorImpl]).to(classOf[RealBillingService])
lLinked Bindings
Linked bindings can also be chained:
In this case, when a CreditCardProcessor is requested, the injector will return
a RealBillingService.
class BillingModule extends Module {
def configure(binder: Binder) ={
binder.bind(classOf[CreditCardProcessor]).to(classOf[PaypalCreditCardProcessor])
binder.bind(classOf[PaypalCreditCardProcessor]).to(classOf[RealBillingService])
}
}
Binding Annotations
We want multiple bindings for a same type.
To enable this, bindings support an optional binding annotation. The
annotation and type together uniquely identify a binding. This pair is
called a key.
To define that annotation you simply add your annotation with your type
Binding Annotations
Named Annotations (built in binding annotation)
Guice comes with a built-in binding annotation @Named that uses a
string:
@ImplementedBy(classOf[RealBillingService])
trait BillingService {
def chargeOrder(order: PizzaOrder, creditCard: CreditCard): String
}
class RealBillingService @Inject() (@Named("real") processor: CreditCardProcessor) extends
BillingService {
/..../
}
Binding Annotations
To bind a specific name, use Names.named() to create an instance to
pass to annotatedWith:
Since the compiler can't check the string, we recommend using @Named
sparingly.
binder.bind(classOf[BillingService])
.annotatedWith(Names.named("real"))
.to(classOf[RealBillingService])
lInstance Bindings
You can bind a type to a specific instance of that type. This is usually
only useful only for objects that don't have dependencies of their own,
such as value objects:
Avoid using .toInstance with objects that are complicated to create,
since it can slow down application startup. You can use an @Provides
method instead.
binder.bind(classOf[String])
.annotatedWith(Names.named("JDBC URL"))
.toInstance("jdbc:mysql://localhost/pizza")
binder.bind(classOf[Int])
.annotatedWith(Names.named("Time Out"))
.toInstance(10)
Untargeted Bindings
You may create bindings without specifying a target.
This is most useful for concrete classes and types annotated by either
@ImplementedBy or @ProvidedBy
An untargetted binding informs the injector about a type, so it may
prepare dependencies eagerly.
Untargetted bindings have no to clause, like so:
binder.bind(classOf[RealBillingService])
binder.bind(classOf[RealBillingService]).in(classOf[Singleton])
Constructor Bindings
Occasionally it's necessary to bind a type to an arbitrary constructor.
This comes up when the @Inject annotation cannot be applied to the
target constructor: because multiple constructors participate in
dependency injection.
To address this, Guice has toConstructor() bindings.
They require you to reflectively select your target constructor and
handle the exception if that constructor cannot be found:
Constructor Bindings
class BillingModule extends Module {
def configure(binder: Binder) = {
try {
binder.bind(classOf[BillingService]).toConstructor(
classOf[RealBillingService].getConstructor(classOf[Connection]));
} catch {
case ex : Exception =>{
println("Exception Occured")
}
}
}
}
Just-in-time Bindings
If a type is needed but there isn't an explicit binding, the injector
will attempt to create a Just-In-Time binding.
These are also known as JIT bindings and implicit bindings.
http://malsup.com/jquery/media/guice.pdf
http://www.journaldev.com/2394/dependency-injection-design-pattern-
in-java-example-tutorial
https://books.google.co.in/books?id=s9Yr6gnhE90C&printsec=frontcover
&source=gbs_ge_summary_r&cad=0#v=onepage&q&f=false
https://github.com/google/guice/wiki/ExternalDocumentation
https://github.com/google/guice/wiki/Motivation
References
Thank you

More Related Content

What's hot

The everyday developer's guide to version control with Git
The everyday developer's guide to version control with GitThe everyday developer's guide to version control with Git
The everyday developer's guide to version control with GitE Carter
 
A Gentle Introduction To Docker And All Things Containers
A Gentle Introduction To Docker And All Things ContainersA Gentle Introduction To Docker And All Things Containers
A Gentle Introduction To Docker And All Things ContainersJérôme Petazzoni
 
Gerrit multi-master / multi-site at GerritHub
Gerrit multi-master / multi-site at GerritHubGerrit multi-master / multi-site at GerritHub
Gerrit multi-master / multi-site at GerritHubLuca Milanesio
 
Kubernetes in Docker
Kubernetes in DockerKubernetes in Docker
Kubernetes in DockerDocker, Inc.
 
Docker Basic to Advance
Docker Basic to AdvanceDocker Basic to Advance
Docker Basic to AdvanceParas Jain
 
Distributed Caching in Kubernetes with Hazelcast
Distributed Caching in Kubernetes with HazelcastDistributed Caching in Kubernetes with Hazelcast
Distributed Caching in Kubernetes with HazelcastMesut Celik
 
Building images efficiently and securely on Kubernetes with BuildKit
Building images efficiently and securely on Kubernetes with BuildKitBuilding images efficiently and securely on Kubernetes with BuildKit
Building images efficiently and securely on Kubernetes with BuildKitNTT Software Innovation Center
 
Comment se préparer pour les certifications Salesforce
Comment se préparer pour les certifications SalesforceComment se préparer pour les certifications Salesforce
Comment se préparer pour les certifications SalesforceDoria Hamelryk
 
쿠버네티스를 이용한 기능 브랜치별 테스트 서버 만들기 (GitOps CI/CD)
쿠버네티스를 이용한 기능 브랜치별 테스트 서버 만들기 (GitOps CI/CD)쿠버네티스를 이용한 기능 브랜치별 테스트 서버 만들기 (GitOps CI/CD)
쿠버네티스를 이용한 기능 브랜치별 테스트 서버 만들기 (GitOps CI/CD)충섭 김
 
The Microservices world in. NET Core and. NET framework
The Microservices world in. NET Core and. NET frameworkThe Microservices world in. NET Core and. NET framework
The Microservices world in. NET Core and. NET frameworkMassimo Bonanni
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring BootTrey Howard
 

What's hot (20)

Blazor web apps
Blazor web appsBlazor web apps
Blazor web apps
 
The everyday developer's guide to version control with Git
The everyday developer's guide to version control with GitThe everyday developer's guide to version control with Git
The everyday developer's guide to version control with Git
 
A Gentle Introduction To Docker And All Things Containers
A Gentle Introduction To Docker And All Things ContainersA Gentle Introduction To Docker And All Things Containers
A Gentle Introduction To Docker And All Things Containers
 
Gerrit multi-master / multi-site at GerritHub
Gerrit multi-master / multi-site at GerritHubGerrit multi-master / multi-site at GerritHub
Gerrit multi-master / multi-site at GerritHub
 
Docker on Docker
Docker on DockerDocker on Docker
Docker on Docker
 
Docker Basics
Docker BasicsDocker Basics
Docker Basics
 
Kubernetes in Docker
Kubernetes in DockerKubernetes in Docker
Kubernetes in Docker
 
Docker Basic to Advance
Docker Basic to AdvanceDocker Basic to Advance
Docker Basic to Advance
 
Distributed Caching in Kubernetes with Hazelcast
Distributed Caching in Kubernetes with HazelcastDistributed Caching in Kubernetes with Hazelcast
Distributed Caching in Kubernetes with Hazelcast
 
Grokking opensource with github
Grokking opensource with githubGrokking opensource with github
Grokking opensource with github
 
Ab initio beginner's course topic 2
Ab initio beginner's course   topic 2Ab initio beginner's course   topic 2
Ab initio beginner's course topic 2
 
Git and github 101
Git and github 101Git and github 101
Git and github 101
 
Building images efficiently and securely on Kubernetes with BuildKit
Building images efficiently and securely on Kubernetes with BuildKitBuilding images efficiently and securely on Kubernetes with BuildKit
Building images efficiently and securely on Kubernetes with BuildKit
 
GitHub Basics - Derek Bable
GitHub Basics - Derek BableGitHub Basics - Derek Bable
GitHub Basics - Derek Bable
 
Dockerfile
Dockerfile Dockerfile
Dockerfile
 
Comment se préparer pour les certifications Salesforce
Comment se préparer pour les certifications SalesforceComment se préparer pour les certifications Salesforce
Comment se préparer pour les certifications Salesforce
 
쿠버네티스를 이용한 기능 브랜치별 테스트 서버 만들기 (GitOps CI/CD)
쿠버네티스를 이용한 기능 브랜치별 테스트 서버 만들기 (GitOps CI/CD)쿠버네티스를 이용한 기능 브랜치별 테스트 서버 만들기 (GitOps CI/CD)
쿠버네티스를 이용한 기능 브랜치별 테스트 서버 만들기 (GitOps CI/CD)
 
Jsf
JsfJsf
Jsf
 
The Microservices world in. NET Core and. NET framework
The Microservices world in. NET Core and. NET frameworkThe Microservices world in. NET Core and. NET framework
The Microservices world in. NET Core and. NET framework
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 

Similar to Introduction to Google Guice Dependency Injection Framework

Inter Process Communication (IPC) in Android
Inter Process Communication (IPC) in AndroidInter Process Communication (IPC) in Android
Inter Process Communication (IPC) in AndroidMalwinder Singh
 
MongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDBMongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDBMongoDB
 
Guice tutorial
Guice tutorialGuice tutorial
Guice tutorialAnh Quân
 
Rc085 010d-vaadin7
Rc085 010d-vaadin7Rc085 010d-vaadin7
Rc085 010d-vaadin7Cosmina Ivan
 
Dsug 05 02-15 - ScalDI - lightweight DI in Scala
Dsug 05 02-15 - ScalDI - lightweight DI in ScalaDsug 05 02-15 - ScalDI - lightweight DI in Scala
Dsug 05 02-15 - ScalDI - lightweight DI in ScalaUgo Matrangolo
 
introduction to Angularjs basics
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basicsRavindra K
 
Angular.js interview questions
Angular.js interview questionsAngular.js interview questions
Angular.js interview questionscodeandyou forums
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDiego Lewin
 
How We Brought Advanced HTML5 Viewing to ADF
How We Brought Advanced HTML5 Viewing to ADFHow We Brought Advanced HTML5 Viewing to ADF
How We Brought Advanced HTML5 Viewing to ADFSeanGraham5
 
Evolving your Data Access with MongoDB Stitch - Drew Di Palma
Evolving your Data Access with MongoDB Stitch - Drew Di PalmaEvolving your Data Access with MongoDB Stitch - Drew Di Palma
Evolving your Data Access with MongoDB Stitch - Drew Di PalmaMongoDB
 

Similar to Introduction to Google Guice Dependency Injection Framework (20)

Guice
GuiceGuice
Guice
 
Guice
GuiceGuice
Guice
 
sfdsdfsdfsdf
sfdsdfsdfsdfsfdsdfsdfsdf
sfdsdfsdfsdf
 
Inter Process Communication (IPC) in Android
Inter Process Communication (IPC) in AndroidInter Process Communication (IPC) in Android
Inter Process Communication (IPC) in Android
 
MongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDBMongoDB.local Atlanta: Introduction to Serverless MongoDB
MongoDB.local Atlanta: Introduction to Serverless MongoDB
 
Google GIN
Google GINGoogle GIN
Google GIN
 
Guice tutorial
Guice tutorialGuice tutorial
Guice tutorial
 
Guice
GuiceGuice
Guice
 
Guice
GuiceGuice
Guice
 
Angularjs Basics
Angularjs BasicsAngularjs Basics
Angularjs Basics
 
Rc085 010d-vaadin7
Rc085 010d-vaadin7Rc085 010d-vaadin7
Rc085 010d-vaadin7
 
Angular js
Angular jsAngular js
Angular js
 
Dsug 05 02-15 - ScalDI - lightweight DI in Scala
Dsug 05 02-15 - ScalDI - lightweight DI in ScalaDsug 05 02-15 - ScalDI - lightweight DI in Scala
Dsug 05 02-15 - ScalDI - lightweight DI in Scala
 
introduction to Angularjs basics
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basics
 
Angular.js interview questions
Angular.js interview questionsAngular.js interview questions
Angular.js interview questions
 
Dependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony ContainerDependency Injection, Zend Framework and Symfony Container
Dependency Injection, Zend Framework and Symfony Container
 
How We Brought Advanced HTML5 Viewing to ADF
How We Brought Advanced HTML5 Viewing to ADFHow We Brought Advanced HTML5 Viewing to ADF
How We Brought Advanced HTML5 Viewing to ADF
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
 
Asp.Net MVC Intro
Asp.Net MVC IntroAsp.Net MVC Intro
Asp.Net MVC Intro
 
Evolving your Data Access with MongoDB Stitch - Drew Di Palma
Evolving your Data Access with MongoDB Stitch - Drew Di PalmaEvolving your Data Access with MongoDB Stitch - Drew Di Palma
Evolving your Data Access with MongoDB Stitch - Drew Di Palma
 

More from Knoldus Inc.

Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxKnoldus Inc.
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxKnoldus Inc.
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxKnoldus Inc.
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxKnoldus Inc.
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationKnoldus Inc.
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationKnoldus Inc.
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIsKnoldus Inc.
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II PresentationKnoldus Inc.
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAKnoldus Inc.
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Knoldus Inc.
 
Azure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxAzure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxKnoldus Inc.
 
The Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinThe Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinKnoldus Inc.
 
Data Engineering with Databricks Presentation
Data Engineering with Databricks PresentationData Engineering with Databricks Presentation
Data Engineering with Databricks PresentationKnoldus Inc.
 
Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Knoldus Inc.
 
NoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxNoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxKnoldus Inc.
 
Mastering Distributed Performance Testing
Mastering Distributed Performance TestingMastering Distributed Performance Testing
Mastering Distributed Performance TestingKnoldus Inc.
 
MLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxMLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxKnoldus Inc.
 
Introduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationIntroduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationKnoldus Inc.
 
CQRS with dot net services presentation.
CQRS with dot net services presentation.CQRS with dot net services presentation.
CQRS with dot net services presentation.Knoldus Inc.
 

More from Knoldus Inc. (20)

Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)
 
Azure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxAzure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptx
 
The Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinThe Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and Kotlin
 
Data Engineering with Databricks Presentation
Data Engineering with Databricks PresentationData Engineering with Databricks Presentation
Data Engineering with Databricks Presentation
 
Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)
 
NoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptxNoOps - (Automate Ops) Presentation.pptx
NoOps - (Automate Ops) Presentation.pptx
 
Mastering Distributed Performance Testing
Mastering Distributed Performance TestingMastering Distributed Performance Testing
Mastering Distributed Performance Testing
 
MLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptxMLops on Vertex AI Presentation (AI/ML).pptx
MLops on Vertex AI Presentation (AI/ML).pptx
 
Introduction to Ansible Tower Presentation
Introduction to Ansible Tower PresentationIntroduction to Ansible Tower Presentation
Introduction to Ansible Tower Presentation
 
CQRS with dot net services presentation.
CQRS with dot net services presentation.CQRS with dot net services presentation.
CQRS with dot net services presentation.
 

Recently uploaded

Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxabhijeetpadhi001
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentInMediaRes1
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfMahmoud M. Sallam
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.arsicmarija21
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Jisc
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersSabitha Banu
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatYousafMalik24
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentInMediaRes1
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
 

Recently uploaded (20)

Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
MICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptxMICROBIOLOGY biochemical test detailed.pptx
MICROBIOLOGY biochemical test detailed.pptx
 
Meghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media ComponentMeghan Sutherland In Media Res Media Component
Meghan Sutherland In Media Res Media Component
 
Pharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdfPharmacognosy Flower 3. Compositae 2023.pdf
Pharmacognosy Flower 3. Compositae 2023.pdf
 
AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.AmericanHighSchoolsprezentacijaoskolama.
AmericanHighSchoolsprezentacijaoskolama.
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...Procuring digital preservation CAN be quick and painless with our new dynamic...
Procuring digital preservation CAN be quick and painless with our new dynamic...
 
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Kamla Market (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
 
DATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginnersDATA STRUCTURE AND ALGORITHM for beginners
DATA STRUCTURE AND ALGORITHM for beginners
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...OS-operating systems- ch04 (Threads) ...
OS-operating systems- ch04 (Threads) ...
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Earth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice greatEarth Day Presentation wow hello nice great
Earth Day Presentation wow hello nice great
 
Alper Gobel In Media Res Media Component
Alper Gobel In Media Res Media ComponentAlper Gobel In Media Res Media Component
Alper Gobel In Media Res Media Component
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
 

Introduction to Google Guice Dependency Injection Framework

  • 1. INTRODUCTION TO GOOGLE GUICE Jyotsna Karan Software Consultant Knoldus Software LLP
  • 2. AGENDA lIntroduction to Dependency Injection lWhat is Google Guice lExploring the Guice API lInjector lModule lGuice lBinder
  • 3. lThe ability to supply (inject) an external dependency into a software component. lTypes of Dependency Injection: lConstructor injection lSetter injection lCake pattern lGoogle-guice What is Dependency Injection
  • 4. Benefits of Dependency Injection lSome of the benefits of using Dependency Injection are: lSeparation of Concerns lBoilerplate Code reduction in application classes because all work to initialize dependencies is handled by the injector component lConfigurable components makes application easily extendable lUnit testing is easy with mock objects
  • 5. Disadvantages of Dependency Injection lIf overused, it can lead to maintenance issues because effect of changes are known at runtime. lDependency injection hides the service class dependencies that can lead to runtime errors that would have been caught at compile time.
  • 6. Exploring Google Guice lGoogle Guice is a Dependency Injection Framework that can be used by Applications where Relation-ship/Dependency between Business Objects have to be maintained manually in the Application code. Trait Storage { def store(data: Data) def retrieve(): String }
  • 7. Exploring Google Guice class FileStorage extends Storage { def store(data: Data) = { // Store the object in a file using Java Serialization mechanism. } def retrieve(): String = { // Code to retrieve the object. "" } } class StorageClient extends App { // Making use of file storage. val storage = new FileStorage(); storage.store(new Data()); }
  • 8. A Simple Guice Example : trait CreditCardProcessor { def charge(): String } class CreditCardProcessorImpl extends CreditCardProcessor { def charge(): String = { // } } trait BillingService { def chargeOrder(order: PizzaOrder, creditCard: CreditCard): String } class RealBillingService @Inject() (processor: CreditCardProcessor) extends BillingService { def chargeOrder(order: PizzaOrder, creditCard: CreditCard): String = { //some code code process order val result = processor.charge() result } }
  • 9. A Simple Guice Example (contd..): class BillingModule extends Module { def configure(binder: Binder) ={ binder.bind(classOf[CreditCardProcessor]).to(classOf[CreditCardProcessorImpl]) binder.bind(classOf[BillingService]).to(classOf[RealBillingService]) } } object GuiceApp extends App { val module = new BillingModule val injector = Guice.createInjector(module) val component = injector.getInstance(classOf[BillingService]) println("Order Successful : " + component.chargeOrder(PizzaOrder("garlicBread", 4), CreditCard())) }
  • 10. Injector Injectors take care of creating and maintaining Objects that are used by the Clients. Injectors do maintain a set of Default Bindings from where they can take the Configuration information of creating and maintaining Relation- ship between Objects. To get all the Bindings associated with the Injector, simply make a call to Injector.getBindings() method which will return a Map of Binding objects. val injector = Guice.createInjector(new BillingModule) val component = injector.getInstance(classOf[BillingService]) val bindings = injector.getBindings
  • 11. Module Module is represented by an interface with a method called Module.configure() which should be overridden by the Application to populate the Bindings. To simplify things, there is a class called AbstractModule which directly extends the Module interface. So Applications can depend on AbstractModule rather than Module. class BillingModule extends Module { def configure(binder: Binder) = { //code that binds the information using various flavours of bind } }
  • 12. lGuice Guice is a class which Clients directly depends upon to interact with other Objects. The Relation-ship between Injector and the various modules is established through this class. For example consider the following code snippet, val module = new BillingModule val injector = Guice.createInjector(module)
  • 13. Binder This interface mainly consists of information related to Bindings. A Binding refers a mapping for an Interface to its corresponding Implementation. For example, we refer that the interface BillingService is bound to RealBillingService implementation. binder.bind(classOf[BillingService]).to(classOf[RealBillingService])
  • 14. Binder To specify how dependencies are resolved, configure your injector with bindings. Creating Bindings To create bindings, extend AbstractModule and override its configure method. In the method body, call bind() to specify each binding. These methods are type checked so the compiler can report errors if you use the wrong types. Once you've created your modules, pass them as arguments to Guice.createInjector() to build an injector.
  • 15. lLinked Bindings Linked bindings map a type to its implementation. This example maps the interface CreditCardProcessor to the implementation CreditCardProcessorImpl: class BillingModule extends Module { def configure(binder: Binder) ={ binder.bind(classOf[CreditCardProcessor]).to(classOf[CreditCardProcessorImpl]) } } binder.bind(classOf[CreditCardProcessorImpl]).to(classOf[RealBillingService])
  • 16. lLinked Bindings Linked bindings can also be chained: In this case, when a CreditCardProcessor is requested, the injector will return a RealBillingService. class BillingModule extends Module { def configure(binder: Binder) ={ binder.bind(classOf[CreditCardProcessor]).to(classOf[PaypalCreditCardProcessor]) binder.bind(classOf[PaypalCreditCardProcessor]).to(classOf[RealBillingService]) } }
  • 17. Binding Annotations We want multiple bindings for a same type. To enable this, bindings support an optional binding annotation. The annotation and type together uniquely identify a binding. This pair is called a key. To define that annotation you simply add your annotation with your type
  • 18. Binding Annotations Named Annotations (built in binding annotation) Guice comes with a built-in binding annotation @Named that uses a string: @ImplementedBy(classOf[RealBillingService]) trait BillingService { def chargeOrder(order: PizzaOrder, creditCard: CreditCard): String } class RealBillingService @Inject() (@Named("real") processor: CreditCardProcessor) extends BillingService { /..../ }
  • 19. Binding Annotations To bind a specific name, use Names.named() to create an instance to pass to annotatedWith: Since the compiler can't check the string, we recommend using @Named sparingly. binder.bind(classOf[BillingService]) .annotatedWith(Names.named("real")) .to(classOf[RealBillingService])
  • 20. lInstance Bindings You can bind a type to a specific instance of that type. This is usually only useful only for objects that don't have dependencies of their own, such as value objects: Avoid using .toInstance with objects that are complicated to create, since it can slow down application startup. You can use an @Provides method instead. binder.bind(classOf[String]) .annotatedWith(Names.named("JDBC URL")) .toInstance("jdbc:mysql://localhost/pizza") binder.bind(classOf[Int]) .annotatedWith(Names.named("Time Out")) .toInstance(10)
  • 21. Untargeted Bindings You may create bindings without specifying a target. This is most useful for concrete classes and types annotated by either @ImplementedBy or @ProvidedBy An untargetted binding informs the injector about a type, so it may prepare dependencies eagerly. Untargetted bindings have no to clause, like so: binder.bind(classOf[RealBillingService]) binder.bind(classOf[RealBillingService]).in(classOf[Singleton])
  • 22. Constructor Bindings Occasionally it's necessary to bind a type to an arbitrary constructor. This comes up when the @Inject annotation cannot be applied to the target constructor: because multiple constructors participate in dependency injection. To address this, Guice has toConstructor() bindings. They require you to reflectively select your target constructor and handle the exception if that constructor cannot be found:
  • 23. Constructor Bindings class BillingModule extends Module { def configure(binder: Binder) = { try { binder.bind(classOf[BillingService]).toConstructor( classOf[RealBillingService].getConstructor(classOf[Connection])); } catch { case ex : Exception =>{ println("Exception Occured") } } } }
  • 24. Just-in-time Bindings If a type is needed but there isn't an explicit binding, the injector will attempt to create a Just-In-Time binding. These are also known as JIT bindings and implicit bindings.