SlideShare a Scribd company logo
Dependency Injection
Aman Verma
Why are we doing this ??
● To learn a new buzz word ??
● To improve code quality ??
● Is this all ??
Dependency injection using Google guice
Problem
We have a simple problem which we need to solve
Let say we have a class, Person, and this class needs
to send a message (Say email).
The Person class requires the aid of some other
class, Email, in order to send a message.
Is this ok ??
For a new Type of Email
For a new param addition to constructor
We have to change every instantiation of Email class
If we change Email to Singleton
For a new Message Delivery System
Design won’t scale with new Message Delivery
systems addition and we will have to make changes
everywhere
Testing
Here we cannot provide a stub
implementation since the class
instantiates the class
TDD is not possible
Case Study
Standard n-tier architecture
Dependency injection using Google guice
Mantra
Inversion of Control
● Invert the controls to achieve loose coupling
● The control means any additional responsibilities a class has other than its main responsibility,
such as control over the flow of an application, control over the flow of an object creation or
dependent object creation and binding. (Don't forget SRP)
● Analogy of Car
● If you want to do TDD then you must use IoC principle without which TDD is not possible.
Don't call us, we'll call you
● Software frameworks, callbacks, schedulers, event loops, dependency injection are examples of
design patterns that follow the inversion of control principle
● Helps in
○ To focus a module on the task it is designed for.
○ To free modules from assumptions about how other systems do what they do and
instead rely on contracts.
○ To prevent side effects when replacing a module.
What’s the issue ?
● Using Factory to achieve Ioc
● Is it ok now ??
Dependency Inversion Principle
● Dependency inversion principle refers to a specific form of decoupling software modules.
● High-level modules should not depend on low-level modules. Both should depend on
abstraction.
● Abstractions should not depend on details. Details should depend on abstractions.
Dependency Inversion Principle
CustomerBusinessLogic and CustomerDataAccess classes
are loosely coupled classes because
CustomerBusinessLogic does not depend on concrete
DataAccess class, instead it includes reference of
ICustomerDataAccess interface. So now, we can easily
use another class which implements
ICustomerDataAccess with different implementation.
Dependency injection using Google guice
Won’t this be awesome ?
Dependency injection using Google guice
● The problem with the solution is that we used DataAccessFactory inside
CustomerBusinessLogic class. So, suppose there is another implementation of
ICustomerDataAccess for some reason and we want to use that new class inside
CustomerBusinessLogic. Then, we need to change the source code of CustomerBusinessLogic
class also. (Violation of Open Closed Principle)
● All the dependencies must be provided externally.
● Can be done via factories
● Can be done via IoC Containers say Google Guice.
Dependency Injection
Dependency injection using Google guice
Google Guice to the rescue
● Guice’s job is to assemble graphs of objects. You request an instance of a given type, and it
figures out what to build, resolves dependencies, and wires everything together.
● Guice alleviates the need for factories and the use of new in your Java code. Think of Guice's
@Inject as the new new.
● Code will be easier to change, unit test and reuse in other contexts.
Guice Bindings - Linked Binding
● Linked bindings map a type to its implementation.
● This example maps the interface TransactionLog to the implementation
DatabaseTransactionLog
● Chaining of Bindings can also be done.
● In this case, when a TransactionLog is requested, the injector will return a
MySqlDatabaseTransactionLog.
Binding Annotations
● What if you want to bind different implementations of interfaces in different contexts ??
● For example, you might want both a PayPal credit card processor and a Google Checkout
processor to be bound to CreditCardProcessor Interface ?
Dependency injection using Google guice
Would I have to create annotations ?
Instance Binding
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:
Provides Binding
● When you need code to create an object, use an @Provides method.
● The method must be defined within a module, and it must have an @Provides annotation.
● Whenever the injector needs an instance of that type, it will invoke the method.
● Guice does not allow exceptions to be thrown from Providers. Exceptions thrown by @Provides
methods will be wrapped in a ProvisionException. It is bad practice to allow any kind of
exception to be thrown -- runtime or checked -- from an @Provides method.
Untargeted Bindings
● You may create bindings without specifying a target. This is most useful for concrete classes
● When specifying binding annotations, you must still add the target binding, even it is the same
concrete class
Just In Time Binding
● The bindings in a modules are called explicit bindings, and the injector uses them whenever
they're available.
● If a type is needed but there isn't an explicit binding, the injector will attempt to create a Just-In-
Time binding.
@ImplementedBy
● Annotate types tell the injector what their default implementation type is.
● The @ImplementedBy annotation acts like a linked binding, specifying the subtype to use when
building a type.
Questions ???

More Related Content

PDF
Getting Started with Kubernetes
PPTX
Introduction to Google Guice
PPT
Google Guice
PDF
PPTX
Intro to git and git hub
PPTX
Git and GitHub | Concept about Git and GitHub Process | Git Process overview
PDF
Introduction to gradle
PDF
CI/CD with Github Actions
Getting Started with Kubernetes
Introduction to Google Guice
Google Guice
Intro to git and git hub
Git and GitHub | Concept about Git and GitHub Process | Git Process overview
Introduction to gradle
CI/CD with Github Actions

What's hot (20)

PPTX
Jenkins CI
PDF
Gitlab ci-cd
PDF
Introduction to Istio on Kubernetes
PPTX
Git & GitLab
PDF
Git - An Introduction
PDF
Introduction to CICD
PDF
github-actions.pdf
PPTX
Service mesh
PDF
Introduction to GitHub Actions
PPTX
Wso2 is integration with .net core
PPTX
Gitlab CI/CD
PPT
OAuth 2.0 and OpenId Connect
PDF
CRI, OCI, and CRI-O
PPTX
Gerrit: how to cook a plugin in only 10 mins
PPTX
Container based CI/CD on GitHub Actions
PDF
Spring Native and Spring AOT
PPTX
Docker introduction
PPTX
What is an API?
PPTX
What Is Docker? | What Is Docker And How It Works? | Docker Tutorial For Begi...
PDF
What Is Kubernetes | Kubernetes Introduction | Kubernetes Tutorial For Beginn...
Jenkins CI
Gitlab ci-cd
Introduction to Istio on Kubernetes
Git & GitLab
Git - An Introduction
Introduction to CICD
github-actions.pdf
Service mesh
Introduction to GitHub Actions
Wso2 is integration with .net core
Gitlab CI/CD
OAuth 2.0 and OpenId Connect
CRI, OCI, and CRI-O
Gerrit: how to cook a plugin in only 10 mins
Container based CI/CD on GitHub Actions
Spring Native and Spring AOT
Docker introduction
What is an API?
What Is Docker? | What Is Docker And How It Works? | Docker Tutorial For Begi...
What Is Kubernetes | Kubernetes Introduction | Kubernetes Tutorial For Beginn...
Ad

Similar to Dependency injection using Google guice (20)

PDF
Mock Objects, Design and Dependency Inversion Principle
PDF
Java onguice20070426
PPTX
Dependency Inversion Principle
PDF
PDF
PDF
Guice
PDF
sfdsdfsdfsdf
PDF
PDF
Guice - dependency injection framework
PDF
Slaying Sacred Cows: Deconstructing Dependency Injection
PDF
Dependency Injection
PPTX
Dependency Injection Inversion Of Control And Unity
PDF
Brief introduction into dependencies
PPTX
L09 Frameworks
PPTX
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
PPTX
Clean Code Part II - Dependency Injection at SoCal Code Camp
PDF
L07 Frameworks
PPTX
Cut your Dependencies with Dependency Injection for East Bay.NET User Group
PPTX
Dependency Injection, Design Principles and Patterns
PPTX
Cut your Dependencies - Dependency Injection at Silicon Valley Code Camp
Mock Objects, Design and Dependency Inversion Principle
Java onguice20070426
Dependency Inversion Principle
Guice
sfdsdfsdfsdf
Guice - dependency injection framework
Slaying Sacred Cows: Deconstructing Dependency Injection
Dependency Injection
Dependency Injection Inversion Of Control And Unity
Brief introduction into dependencies
L09 Frameworks
Cut your Dependencies with Dependency Injection - .NET User Group Osnabrueck
Clean Code Part II - Dependency Injection at SoCal Code Camp
L07 Frameworks
Cut your Dependencies with Dependency Injection for East Bay.NET User Group
Dependency Injection, Design Principles and Patterns
Cut your Dependencies - Dependency Injection at Silicon Valley Code Camp
Ad

Recently uploaded (20)

PPTX
Lecture Notes Electrical Wiring System Components
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PDF
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PDF
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PPT
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
PPTX
Internet of Things (IOT) - A guide to understanding
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
additive manufacturing of ss316l using mig welding
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PDF
Automation-in-Manufacturing-Chapter-Introduction.pdf
PPTX
web development for engineering and engineering
PPT
Mechanical Engineering MATERIALS Selection
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PDF
PPT on Performance Review to get promotions
PPTX
Sustainable Sites - Green Building Construction
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
UNIT 4 Total Quality Management .pptx
Lecture Notes Electrical Wiring System Components
Foundation to blockchain - A guide to Blockchain Tech
BMEC211 - INTRODUCTION TO MECHATRONICS-1.pdf
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
TFEC-4-2020-Design-Guide-for-Timber-Roof-Trusses.pdf
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
Internet of Things (IOT) - A guide to understanding
OOP with Java - Java Introduction (Basics)
additive manufacturing of ss316l using mig welding
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
Automation-in-Manufacturing-Chapter-Introduction.pdf
web development for engineering and engineering
Mechanical Engineering MATERIALS Selection
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPT on Performance Review to get promotions
Sustainable Sites - Green Building Construction
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
UNIT 4 Total Quality Management .pptx

Dependency injection using Google guice

  • 2. Why are we doing this ?? ● To learn a new buzz word ?? ● To improve code quality ?? ● Is this all ??
  • 4. Problem We have a simple problem which we need to solve Let say we have a class, Person, and this class needs to send a message (Say email). The Person class requires the aid of some other class, Email, in order to send a message.
  • 6. For a new Type of Email
  • 7. For a new param addition to constructor We have to change every instantiation of Email class
  • 8. If we change Email to Singleton
  • 9. For a new Message Delivery System Design won’t scale with new Message Delivery systems addition and we will have to make changes everywhere
  • 10. Testing Here we cannot provide a stub implementation since the class instantiates the class TDD is not possible
  • 14. Inversion of Control ● Invert the controls to achieve loose coupling ● The control means any additional responsibilities a class has other than its main responsibility, such as control over the flow of an application, control over the flow of an object creation or dependent object creation and binding. (Don't forget SRP) ● Analogy of Car ● If you want to do TDD then you must use IoC principle without which TDD is not possible.
  • 15. Don't call us, we'll call you ● Software frameworks, callbacks, schedulers, event loops, dependency injection are examples of design patterns that follow the inversion of control principle ● Helps in ○ To focus a module on the task it is designed for. ○ To free modules from assumptions about how other systems do what they do and instead rely on contracts. ○ To prevent side effects when replacing a module.
  • 17. ● Using Factory to achieve Ioc ● Is it ok now ??
  • 18. Dependency Inversion Principle ● Dependency inversion principle refers to a specific form of decoupling software modules. ● High-level modules should not depend on low-level modules. Both should depend on abstraction. ● Abstractions should not depend on details. Details should depend on abstractions.
  • 20. CustomerBusinessLogic and CustomerDataAccess classes are loosely coupled classes because CustomerBusinessLogic does not depend on concrete DataAccess class, instead it includes reference of ICustomerDataAccess interface. So now, we can easily use another class which implements ICustomerDataAccess with different implementation.
  • 22. Won’t this be awesome ?
  • 24. ● The problem with the solution is that we used DataAccessFactory inside CustomerBusinessLogic class. So, suppose there is another implementation of ICustomerDataAccess for some reason and we want to use that new class inside CustomerBusinessLogic. Then, we need to change the source code of CustomerBusinessLogic class also. (Violation of Open Closed Principle) ● All the dependencies must be provided externally. ● Can be done via factories ● Can be done via IoC Containers say Google Guice. Dependency Injection
  • 26. Google Guice to the rescue ● Guice’s job is to assemble graphs of objects. You request an instance of a given type, and it figures out what to build, resolves dependencies, and wires everything together. ● Guice alleviates the need for factories and the use of new in your Java code. Think of Guice's @Inject as the new new. ● Code will be easier to change, unit test and reuse in other contexts.
  • 27. Guice Bindings - Linked Binding ● Linked bindings map a type to its implementation. ● This example maps the interface TransactionLog to the implementation DatabaseTransactionLog
  • 28. ● Chaining of Bindings can also be done. ● In this case, when a TransactionLog is requested, the injector will return a MySqlDatabaseTransactionLog.
  • 29. Binding Annotations ● What if you want to bind different implementations of interfaces in different contexts ?? ● For example, you might want both a PayPal credit card processor and a Google Checkout processor to be bound to CreditCardProcessor Interface ?
  • 31. Would I have to create annotations ?
  • 32. Instance Binding 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:
  • 33. Provides Binding ● When you need code to create an object, use an @Provides method. ● The method must be defined within a module, and it must have an @Provides annotation. ● Whenever the injector needs an instance of that type, it will invoke the method. ● Guice does not allow exceptions to be thrown from Providers. Exceptions thrown by @Provides methods will be wrapped in a ProvisionException. It is bad practice to allow any kind of exception to be thrown -- runtime or checked -- from an @Provides method.
  • 34. Untargeted Bindings ● You may create bindings without specifying a target. This is most useful for concrete classes ● When specifying binding annotations, you must still add the target binding, even it is the same concrete class
  • 35. Just In Time Binding ● The bindings in a modules are called explicit bindings, and the injector uses them whenever they're available. ● If a type is needed but there isn't an explicit binding, the injector will attempt to create a Just-In- Time binding.
  • 36. @ImplementedBy ● Annotate types tell the injector what their default implementation type is. ● The @ImplementedBy annotation acts like a linked binding, specifying the subtype to use when building a type.