SlideShare a Scribd company logo
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 (20)

KEY
Git and GitHub
James Gray
 
PPTX
Explain Delegates step by step.
Questpond
 
PPTX
Solid principles
Monica Rodrigues
 
PPTX
C# Delegates
Prem Kumar Badri
 
PPTX
Introduction to Docker - 2017
Docker, Inc.
 
PPTX
DESIGN PATTERNS: Strategy Patterns
International Institute of Information Technology (I²IT)
 
PDF
Nodejs presentation
Arvind Devaraj
 
PDF
Your own full blown Gerrit plugin
Dariusz Łuksza
 
PPTX
Git branching strategies
jstack
 
PPTX
Lombok
Amit Aggarwal
 
PPTX
Introduction to Git and GitHub
Bioinformatics and Computational Biosciences Branch
 
PDF
Learning git
Sid Anand
 
PPT
CI and CD with Jenkins
Martin Málek
 
PPT
Design Pattern For C# Part 1
Shahzad
 
PDF
Git training v10
Skander Hamza
 
PPTX
Git Tutorial For Beginners | What is Git and GitHub? | DevOps Tools | DevOps ...
Simplilearn
 
PPTX
Domain Driven Design: Zero to Hero
Fabrício Rissetto
 
PPTX
Design pattern (Abstract Factory & Singleton)
paramisoft
 
PDF
Git
Mayank Patel
 
PDF
Kubernetes GitOps featuring GitHub, Kustomize and ArgoCD
Sunnyvale
 
Git and GitHub
James Gray
 
Explain Delegates step by step.
Questpond
 
Solid principles
Monica Rodrigues
 
C# Delegates
Prem Kumar Badri
 
Introduction to Docker - 2017
Docker, Inc.
 
Nodejs presentation
Arvind Devaraj
 
Your own full blown Gerrit plugin
Dariusz Łuksza
 
Git branching strategies
jstack
 
Learning git
Sid Anand
 
CI and CD with Jenkins
Martin Málek
 
Design Pattern For C# Part 1
Shahzad
 
Git training v10
Skander Hamza
 
Git Tutorial For Beginners | What is Git and GitHub? | DevOps Tools | DevOps ...
Simplilearn
 
Domain Driven Design: Zero to Hero
Fabrício Rissetto
 
Design pattern (Abstract Factory & Singleton)
paramisoft
 
Kubernetes GitOps featuring GitHub, Kustomize and ArgoCD
Sunnyvale
 

Similar to Introduction to Google Guice (20)

PDF
Guice
André Paiva
 
PDF
Guice
André Paiva
 
PDF
Guice
aina1205
 
PDF
sfdsdfsdfsdf
guesta5433ea
 
PDF
Guice
guestd420a8
 
PDF
Java onguice20070426
Ratul Ray
 
PDF
Guice - dependency injection framework
Evgeny Barabanov
 
PPTX
Eway google-guice presentation
Eway Joint Stock Company
 
PDF
Devoxx 2012 (v2)
Jerome Dochez
 
KEY
BeScala - Scala Guice
BeScala
 
PDF
Google guice
Diego Pacheco
 
PDF
Dependency injection in Java, from naive to functional
Marian Wamsiedel
 
PDF
Mock Objects, Design and Dependency Inversion Principle
P Heinonen
 
PDF
Jug Guice Presentation
Dmitry Buzdin
 
PPTX
Implement Dependency Injection in Java
Geng-Dian Huang
 
PDF
guice-servlet
Masaaki Yonebayashi
 
PDF
Brief introduction into dependencies
Joel Krebs
 
PDF
Slaying Sacred Cows: Deconstructing Dependency Injection
Tomer Gabel
 
PPTX
Responsible DI: Ditch the Frameworks
kenbot
 
PDF
L07 Frameworks
Ólafur Andri Ragnarsson
 
Guice
aina1205
 
sfdsdfsdfsdf
guesta5433ea
 
Java onguice20070426
Ratul Ray
 
Guice - dependency injection framework
Evgeny Barabanov
 
Eway google-guice presentation
Eway Joint Stock Company
 
Devoxx 2012 (v2)
Jerome Dochez
 
BeScala - Scala Guice
BeScala
 
Google guice
Diego Pacheco
 
Dependency injection in Java, from naive to functional
Marian Wamsiedel
 
Mock Objects, Design and Dependency Inversion Principle
P Heinonen
 
Jug Guice Presentation
Dmitry Buzdin
 
Implement Dependency Injection in Java
Geng-Dian Huang
 
guice-servlet
Masaaki Yonebayashi
 
Brief introduction into dependencies
Joel Krebs
 
Slaying Sacred Cows: Deconstructing Dependency Injection
Tomer Gabel
 
Responsible DI: Ditch the Frameworks
kenbot
 
L07 Frameworks
Ólafur Andri Ragnarsson
 
Ad

More from Knoldus Inc. (20)

PPTX
Angular Hydration Presentation (FrontEnd)
Knoldus Inc.
 
PPTX
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
Knoldus Inc.
 
PPTX
Self-Healing Test Automation Framework - Healenium
Knoldus Inc.
 
PPTX
Kanban Metrics Presentation (Project Management)
Knoldus Inc.
 
PPTX
Java 17 features and implementation.pptx
Knoldus Inc.
 
PPTX
Chaos Mesh Introducing Chaos in Kubernetes
Knoldus Inc.
 
PPTX
GraalVM - A Step Ahead of JVM Presentation
Knoldus Inc.
 
PPTX
Nomad by HashiCorp Presentation (DevOps)
Knoldus Inc.
 
PPTX
Nomad by HashiCorp Presentation (DevOps)
Knoldus Inc.
 
PPTX
DAPR - Distributed Application Runtime Presentation
Knoldus Inc.
 
PPTX
Introduction to Azure Virtual WAN Presentation
Knoldus Inc.
 
PPTX
Introduction to Argo Rollouts Presentation
Knoldus Inc.
 
PPTX
Intro to Azure Container App Presentation
Knoldus Inc.
 
PPTX
Insights Unveiled Test Reporting and Observability Excellence
Knoldus Inc.
 
PPTX
Introduction to Splunk Presentation (DevOps)
Knoldus Inc.
 
PPTX
Code Camp - Data Profiling and Quality Analysis Framework
Knoldus Inc.
 
PPTX
AWS: Messaging Services in AWS Presentation
Knoldus Inc.
 
PPTX
Amazon Cognito: A Primer on Authentication and Authorization
Knoldus Inc.
 
PPTX
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
Knoldus Inc.
 
PPTX
Managing State & HTTP Requests In Ionic.
Knoldus Inc.
 
Angular Hydration Presentation (FrontEnd)
Knoldus Inc.
 
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
Knoldus Inc.
 
Self-Healing Test Automation Framework - Healenium
Knoldus Inc.
 
Kanban Metrics Presentation (Project Management)
Knoldus Inc.
 
Java 17 features and implementation.pptx
Knoldus Inc.
 
Chaos Mesh Introducing Chaos in Kubernetes
Knoldus Inc.
 
GraalVM - A Step Ahead of JVM Presentation
Knoldus Inc.
 
Nomad by HashiCorp Presentation (DevOps)
Knoldus Inc.
 
Nomad by HashiCorp Presentation (DevOps)
Knoldus Inc.
 
DAPR - Distributed Application Runtime Presentation
Knoldus Inc.
 
Introduction to Azure Virtual WAN Presentation
Knoldus Inc.
 
Introduction to Argo Rollouts Presentation
Knoldus Inc.
 
Intro to Azure Container App Presentation
Knoldus Inc.
 
Insights Unveiled Test Reporting and Observability Excellence
Knoldus Inc.
 
Introduction to Splunk Presentation (DevOps)
Knoldus Inc.
 
Code Camp - Data Profiling and Quality Analysis Framework
Knoldus Inc.
 
AWS: Messaging Services in AWS Presentation
Knoldus Inc.
 
Amazon Cognito: A Primer on Authentication and Authorization
Knoldus Inc.
 
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
Knoldus Inc.
 
Managing State & HTTP Requests In Ionic.
Knoldus Inc.
 
Ad

Recently uploaded (20)

PPTX
PPT on the Development of Education in the Victorian England
Beena E S
 
PPTX
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
PDF
IMP NAAC REFORMS 2024 - 10 Attributes.pdf
BHARTIWADEKAR
 
PPTX
Quarter1-English3-W4-Identifying Elements of the Story
FLORRACHELSANTOS
 
PPTX
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
PPTX
How to Create Rental Orders in Odoo 18 Rental
Celine George
 
PDF
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
PPTX
Capitol Doctoral Presentation -July 2025.pptx
CapitolTechU
 
PPTX
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
PPTX
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
PPTX
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
PPSX
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
PPTX
How to Manage Access Rights & User Types in Odoo 18
Celine George
 
PPTX
BANDHA (BANDAGES) PPT.pptx ayurveda shalya tantra
rakhan78619
 
PPTX
How to Set Maximum Difference Odoo 18 POS
Celine George
 
PDF
IMP NAAC-Reforms-Stakeholder-Consultation-Presentation-on-Draft-Metrics-Unive...
BHARTIWADEKAR
 
PDF
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
PDF
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
PPTX
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
PDF
CHILD RIGHTS AND PROTECTION QUESTION BANK
Dr Raja Mohammed T
 
PPT on the Development of Education in the Victorian England
Beena E S
 
STAFF DEVELOPMENT AND WELFARE: MANAGEMENT
PRADEEP ABOTHU
 
IMP NAAC REFORMS 2024 - 10 Attributes.pdf
BHARTIWADEKAR
 
Quarter1-English3-W4-Identifying Elements of the Story
FLORRACHELSANTOS
 
Growth and development and milestones, factors
BHUVANESHWARI BADIGER
 
How to Create Rental Orders in Odoo 18 Rental
Celine George
 
ARAL_Orientation_Day-2-Sessions_ARAL-Readung ARAL-Mathematics ARAL-Sciencev2.pdf
JoelVilloso1
 
Capitol Doctoral Presentation -July 2025.pptx
CapitolTechU
 
A PPT on Alfred Lord Tennyson's Ulysses.
Beena E S
 
ASRB NET 2023 PREVIOUS YEAR QUESTION PAPER GENETICS AND PLANT BREEDING BY SAT...
Krashi Coaching
 
2025 Winter SWAYAM NPTEL & A Student.pptx
Utsav Yagnik
 
HEALTH ASSESSMENT (Community Health Nursing) - GNM 1st Year
Priyanshu Anand
 
How to Manage Access Rights & User Types in Odoo 18
Celine George
 
BANDHA (BANDAGES) PPT.pptx ayurveda shalya tantra
rakhan78619
 
How to Set Maximum Difference Odoo 18 POS
Celine George
 
IMP NAAC-Reforms-Stakeholder-Consultation-Presentation-on-Draft-Metrics-Unive...
BHARTIWADEKAR
 
CONCURSO DE POESIA “POETUFAS – PASSOS SUAVES PELO VERSO.pdf
Colégio Santa Teresinha
 
Generative AI: it's STILL not a robot (CIJ Summer 2025)
Paul Bradshaw
 
Unit 2 COMMERCIAL BANKING, Corporate banking.pptx
AnubalaSuresh1
 
CHILD RIGHTS AND PROTECTION QUESTION BANK
Dr Raja Mohammed T
 

Introduction to Google Guice

  • 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.