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
Ad

More Related Content

What's hot (20)

Apache Zookeeper
Apache ZookeeperApache Zookeeper
Apache Zookeeper
Nguyen Quang
 
Federated Cloud Computing - The OpenNebula Experience v1.0s
Federated Cloud Computing  - The OpenNebula Experience v1.0sFederated Cloud Computing  - The OpenNebula Experience v1.0s
Federated Cloud Computing - The OpenNebula Experience v1.0s
Ignacio M. Llorente
 
Parallel Database
Parallel DatabaseParallel Database
Parallel Database
VESIT/University of Mumbai
 
The Basics of MongoDB
The Basics of MongoDBThe Basics of MongoDB
The Basics of MongoDB
valuebound
 
Kubernetes - A Comprehensive Overview
Kubernetes - A Comprehensive OverviewKubernetes - A Comprehensive Overview
Kubernetes - A Comprehensive Overview
Bob Killen
 
Container orchestration overview
Container orchestration overviewContainer orchestration overview
Container orchestration overview
Wyn B. Van Devanter
 
Introduction to docker
Introduction to dockerIntroduction to docker
Introduction to docker
Frederik Mogensen
 
Pig Tutorial | Apache Pig Tutorial | What Is Pig In Hadoop? | Apache Pig Arch...
Pig Tutorial | Apache Pig Tutorial | What Is Pig In Hadoop? | Apache Pig Arch...Pig Tutorial | Apache Pig Tutorial | What Is Pig In Hadoop? | Apache Pig Arch...
Pig Tutorial | Apache Pig Tutorial | What Is Pig In Hadoop? | Apache Pig Arch...
Simplilearn
 
Deep Dive into Docker Swarm Mode
Deep Dive into Docker Swarm ModeDeep Dive into Docker Swarm Mode
Deep Dive into Docker Swarm Mode
Ajeet Singh Raina
 
Kubernetes for Beginners: An Introductory Guide
Kubernetes for Beginners: An Introductory GuideKubernetes for Beginners: An Introductory Guide
Kubernetes for Beginners: An Introductory Guide
Bytemark
 
Dockerfile
Dockerfile Dockerfile
Dockerfile
Jeffrey Ellin
 
What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...
What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...
What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...
Simplilearn
 
Apache hive introduction
Apache hive introductionApache hive introduction
Apache hive introduction
Mahmood Reza Esmaili Zand
 
python and database
python and databasepython and database
python and database
Kwangyoun Jung
 
Introduction to Docker Compose
Introduction to Docker ComposeIntroduction to Docker Compose
Introduction to Docker Compose
Ajeet Singh Raina
 
Software Engineering - chp4- design patterns
Software Engineering - chp4- design patternsSoftware Engineering - chp4- design patterns
Software Engineering - chp4- design patterns
Lilia Sfaxi
 
Software architecture with SOA modeling Flavor
Software architecture with SOA modeling FlavorSoftware architecture with SOA modeling Flavor
Software architecture with SOA modeling Flavor
Mohamed Zakarya Abdelgawad
 
Apache Pig: A big data processor
Apache Pig: A big data processorApache Pig: A big data processor
Apache Pig: A big data processor
Tushar B Kute
 
Dependency injection presentation
Dependency injection presentationDependency injection presentation
Dependency injection presentation
Ahasanul Kalam Akib
 
Apache Sqoop: A Data Transfer Tool for Hadoop
Apache Sqoop: A Data Transfer Tool for HadoopApache Sqoop: A Data Transfer Tool for Hadoop
Apache Sqoop: A Data Transfer Tool for Hadoop
Cloudera, Inc.
 
Federated Cloud Computing - The OpenNebula Experience v1.0s
Federated Cloud Computing  - The OpenNebula Experience v1.0sFederated Cloud Computing  - The OpenNebula Experience v1.0s
Federated Cloud Computing - The OpenNebula Experience v1.0s
Ignacio M. Llorente
 
The Basics of MongoDB
The Basics of MongoDBThe Basics of MongoDB
The Basics of MongoDB
valuebound
 
Kubernetes - A Comprehensive Overview
Kubernetes - A Comprehensive OverviewKubernetes - A Comprehensive Overview
Kubernetes - A Comprehensive Overview
Bob Killen
 
Container orchestration overview
Container orchestration overviewContainer orchestration overview
Container orchestration overview
Wyn B. Van Devanter
 
Pig Tutorial | Apache Pig Tutorial | What Is Pig In Hadoop? | Apache Pig Arch...
Pig Tutorial | Apache Pig Tutorial | What Is Pig In Hadoop? | Apache Pig Arch...Pig Tutorial | Apache Pig Tutorial | What Is Pig In Hadoop? | Apache Pig Arch...
Pig Tutorial | Apache Pig Tutorial | What Is Pig In Hadoop? | Apache Pig Arch...
Simplilearn
 
Deep Dive into Docker Swarm Mode
Deep Dive into Docker Swarm ModeDeep Dive into Docker Swarm Mode
Deep Dive into Docker Swarm Mode
Ajeet Singh Raina
 
Kubernetes for Beginners: An Introductory Guide
Kubernetes for Beginners: An Introductory GuideKubernetes for Beginners: An Introductory Guide
Kubernetes for Beginners: An Introductory Guide
Bytemark
 
What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...
What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...
What Is A Docker Container? | Docker Container Tutorial For Beginners| Docker...
Simplilearn
 
Introduction to Docker Compose
Introduction to Docker ComposeIntroduction to Docker Compose
Introduction to Docker Compose
Ajeet Singh Raina
 
Software Engineering - chp4- design patterns
Software Engineering - chp4- design patternsSoftware Engineering - chp4- design patterns
Software Engineering - chp4- design patterns
Lilia Sfaxi
 
Software architecture with SOA modeling Flavor
Software architecture with SOA modeling FlavorSoftware architecture with SOA modeling Flavor
Software architecture with SOA modeling Flavor
Mohamed Zakarya Abdelgawad
 
Apache Pig: A big data processor
Apache Pig: A big data processorApache Pig: A big data processor
Apache Pig: A big data processor
Tushar B Kute
 
Dependency injection presentation
Dependency injection presentationDependency injection presentation
Dependency injection presentation
Ahasanul Kalam Akib
 
Apache Sqoop: A Data Transfer Tool for Hadoop
Apache Sqoop: A Data Transfer Tool for HadoopApache Sqoop: A Data Transfer Tool for Hadoop
Apache Sqoop: A Data Transfer Tool for Hadoop
Cloudera, Inc.
 

Similar to Introduction to Google Guice (20)

Guice
GuiceGuice
Guice
guestd420a8
 
sfdsdfsdfsdf
sfdsdfsdfsdfsfdsdfsdfsdf
sfdsdfsdfsdf
guesta5433ea
 
Guice
GuiceGuice
Guice
aina1205
 
Inter Process Communication (IPC) in Android
Inter Process Communication (IPC) in AndroidInter Process Communication (IPC) in Android
Inter Process Communication (IPC) in Android
Malwinder 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 MongoDB
MongoDB
 
Guice tutorial
Guice tutorialGuice tutorial
Guice tutorial
Anh Quân
 
Google GIN
Google GINGoogle GIN
Google GIN
Anh Quân
 
Guice
GuiceGuice
Guice
André Paiva
 
Guice
GuiceGuice
Guice
André Paiva
 
Angularjs Basics
Angularjs BasicsAngularjs Basics
Angularjs Basics
Anuradha Bandara
 
Rc085 010d-vaadin7
Rc085 010d-vaadin7Rc085 010d-vaadin7
Rc085 010d-vaadin7
Cosmina Ivan
 
Angular js
Angular jsAngular js
Angular js
Silver Touch Technologies Ltd
 
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
Ugo Matrangolo
 
Angular Framework ppt for beginners and advanced
Angular Framework ppt for beginners and advancedAngular Framework ppt for beginners and advanced
Angular Framework ppt for beginners and advanced
Preetha Ganapathi
 
introduction to Angularjs basics
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basics
Ravindra K
 
Angular.js interview questions
Angular.js interview questionsAngular.js interview questions
Angular.js interview questions
codeandyou 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 Container
Diego 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 ADF
SeanGraham5
 
Tdd,Ioc
Tdd,IocTdd,Ioc
Tdd,Ioc
Antonio Radesca
 
Asp.Net MVC Intro
Asp.Net MVC IntroAsp.Net MVC Intro
Asp.Net MVC Intro
Stefano Paluello
 
Inter Process Communication (IPC) in Android
Inter Process Communication (IPC) in AndroidInter Process Communication (IPC) in Android
Inter Process Communication (IPC) in Android
Malwinder 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 MongoDB
MongoDB
 
Guice tutorial
Guice tutorialGuice tutorial
Guice tutorial
Anh Quân
 
Rc085 010d-vaadin7
Rc085 010d-vaadin7Rc085 010d-vaadin7
Rc085 010d-vaadin7
Cosmina 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 Scala
Ugo Matrangolo
 
Angular Framework ppt for beginners and advanced
Angular Framework ppt for beginners and advancedAngular Framework ppt for beginners and advanced
Angular Framework ppt for beginners and advanced
Preetha Ganapathi
 
introduction to Angularjs basics
introduction to Angularjs basicsintroduction to Angularjs basics
introduction to Angularjs basics
Ravindra K
 
Angular.js interview questions
Angular.js interview questionsAngular.js interview questions
Angular.js interview questions
codeandyou 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 Container
Diego 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 ADF
SeanGraham5
 
Ad

More from Knoldus Inc. (20)

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

Recently uploaded (20)

How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
Handling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptxHandling Multiple Choice Responses: Fortune Effiong.pptx
Handling Multiple Choice Responses: Fortune Effiong.pptx
AuthorAIDNationalRes
 
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam SuccessUltimate VMware 2V0-11.25 Exam Dumps for Exam Success
Ultimate VMware 2V0-11.25 Exam Dumps for Exam Success
Mark Soia
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Introduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe EngineeringIntroduction to Vibe Coding and Vibe Engineering
Introduction to Vibe Coding and Vibe Engineering
Damian T. Gordon
 
GDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptxGDGLSPGCOER - Git and GitHub Workshop.pptx
GDGLSPGCOER - Git and GitHub Workshop.pptx
azeenhodekar
 
Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025Stein, Hunt, Green letter to Congress April 2025
Stein, Hunt, Green letter to Congress April 2025
Mebane Rash
 
Unit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdfUnit 6_Introduction_Phishing_Password Cracking.pdf
Unit 6_Introduction_Phishing_Password Cracking.pdf
KanchanPatil34
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
apa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdfapa-style-referencing-visual-guide-2025.pdf
apa-style-referencing-visual-guide-2025.pdf
Ishika Ghosh
 
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdfExploring-Substances-Acidic-Basic-and-Neutral.pdf
Exploring-Substances-Acidic-Basic-and-Neutral.pdf
Sandeep Swamy
 
One Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learningOne Hot encoding a revolution in Machine learning
One Hot encoding a revolution in Machine learning
momer9505
 
How to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odooHow to Set warnings for invoicing specific customers in odoo
How to Set warnings for invoicing specific customers in odoo
Celine George
 
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...Multi-currency in odoo accounting and Update exchange rates automatically in ...
Multi-currency in odoo accounting and Update exchange rates automatically in ...
Celine George
 

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.