Dependency Injection Frameworks Technion – Institute of Technology 236700 1 Author: Assaf Israel - Technion 2013 ©

Slides:



Advertisements
Similar presentations
Spring, Hibernate and Web Services 13 th September 2014.
Advertisements

CSCI 1100/1202 April 3, Testing A program should be executed multiple times with various input in an attempt to find errors Debugging is the process.
Chapter 8 Inheritance Part 2. © 2004 Pearson Addison-Wesley. All rights reserved8-2 Outline Creating Subclasses Overriding Methods Class Hierarchies Inheritance.
Object-Oriented PHP (1)
CS 2511 Fall  Abstraction Abstract class Interfaces  Encapsulation Access Specifiers Data Hiding  Inheritance  Polymorphism.
Software Issues Derived from Dr. Fawcett’s Slides Phil Pratt-Szeliga Fall 2009.
Intro to Spring CJUG - January What is Spring? “The Spring framework provides central transaction control of various objects.” This means that any.
Struts 2.0 an Overview ( )
CVSQL 2 The Design. System Overview System Components CVSQL Server –Three network interfaces –Modular data source provider framework –Decoupled SQL parsing.
Creational Patterns Making Objects The Smart Way Brent Ramerth Abstract Factory, Builder.
Dependency Injection and Model-View-Controller. Overview Inversion of Control Model-View-Controller.
Starting Chapter 4 Starting. 1 Course Outline* Covered in first half until Dr. Li takes over. JAVA and OO: Review what is Object Oriented Programming.
UFCEUS-20-2 : Web Programming Lecture 5 : Object Oriented PHP (1)
Programming Languages and Paradigms Object-Oriented Programming.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Java Classes, Interfaces, and Types 1.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
Monads Technion – Institute of Technology Software Design (236700) Author: Gal Lalouche - Technion 2015 © 1.
Separation of Concerns Technion – Institute of Technology Author: Gal Lalouche - Technion 2015 © 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Spring core v3.x Prepared by: Nhan Le. History v3.0 Spring Expression Language Java based bean metadata v3.1 Cache Abstraction Bean Definition Profile.
1 Chapter 10: Data Abstraction and Object Orientation Aaron Bloomfield CS 415 Fall 2005.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Creational Patterns CSE301 University of Sunderland Harry R Erwin, PhD.
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Test Isolation and Mocking Technion – Institute of Technology Author: Gal Lalouche © 1 Author: Gal Lalouche - Technion 2015 ©
Dependency Injection Technion – Institute of Technology Author: Gal Lalouche - Technion 2015 ©
(c) University of Washington01-1 CSC 143 Java Programming as Modeling Reading: Ch. 1-6.
The Factory Patterns SE-2811 Dr. Mark L. Hornick 1.
Refactoring for Testability (or how I learned to stop worrying and love failing tests) Presented by Aaron Evans.
Object-Oriented Design CSC 212. Announcements This course is speeding up and we are starting new material. Please see me if you feel this is going too.
CSSE501 Object-Oriented Development. Chapter 4: Classes and Methods  Chapters 4 and 5 present two sides of OOP: Chapter 4 discusses the static, compile.
Week 2, Day 2: The Factory Method Pattern Other good design principles Cohesion vs. Coupling Implementing the Strategy Pattern Changing strategies (behaviors)
The Strategy Pattern SE-2811 Dr. Mark L. Hornick 1 Class 1-2.
1 More OO Design Patterns CSC 335: Object-Oriented Programming and Design.
Magnus
Summing Up Object Oriented Design. Four Major Components: Abstraction modeling real-life entities by essential information only Encapsulation clustering.
CSCI 1100/1202 April 1-3, Program Development The creation of software involves four basic activities: –establishing the requirements –creating.
Inheritance Revisited Other Issues. Multiple Inheritance Also called combination--not permitted in Java, but is used in C++ Also called combination--not.
Object Oriented Programming
The Strategy Pattern SE-2811 Dr. Mark L. Hornick 1.
Java EE - Dependency Injection -
Spring and DWR Frameworks for Rich Web Enterprise Application Thomas Wiradikusuma Presentation to the 20 th.
The Factory Method Pattern (Creational) ©SoftMoore ConsultingSlide 1.
Advanced Object-oriented Design Patterns Creational Design Patterns.
1 More OO Design Patterns CSC 335: Object-Oriented Programming and Design.
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design.
Abstract Factory Pattern Jiaxin Wang CSPP Winter 2010.
Dependency Injection with Guice Technion – Institute of Technology Author: Gal Lalouche - Technion 2016 ©
Comp1004: Building Better Objects II Encapsulation and Constructors.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Test Isolation and Mocking Technion – Institute of Technology Author: Gal Lalouche © 1 Author: Gal Lalouche - Technion 2016 ©
1 Creational Design Patterns CSC 335: Object-Oriented Programming and Design.
Abstract Factory Pattern
How to be a Good Developer
MPCS – Advanced java Programming
Test Isolation and Mocking
Low Budget Productions, LLC
Inheritance and Polymorphism
Design Patterns I Technion – Institute of Technology
Abstract Factory Pattern
Intent (Thanks to Jim Fawcett for the slides)
Java Programming Language
Advanced Java Programming
SE-2811 Software Component Design
Tuesday Brown Bag Inversion of Control with Howard Abrams
Chapter 14 Abstract Classes and Interfaces
Designing For Testability
Object-Oriented PHP (1)
Plug-In Architecture Pattern
Presentation transcript:

Dependency Injection Frameworks Technion – Institute of Technology Author: Assaf Israel - Technion 2013 ©

Dependency Injection – Drawbacks (deep) What happens when we need to perform deep injections with no defaults? Consider the following simple design: A is dependent on B, which is dependent on C, which is dependent on D … In order to create an instance of A, we need to inject it with an instance of B, which needs to be injected with an instance of C which needs to be injected with an instance of D … A a = new AImpl(new BImpl(new CImpl(new DImpl()))); What if each class has two or more dependencies? What happens if we have parallel dependencies? e.g., one for local database, another for cloud management, one for development It is hard to wire everything up without mistakes We could just put everything in a single abstract factory… …but that breaks encapsulation Author: Gal Lalouche - Technion 2015 © 2

Dependency Injection Frameworks Completely separate object configuration from creation, allowing for cleaner code Can inject recursively Easy to manage parallel instantiations Author: Gal Lalouche - Technion 2015 © 3

Dependency Injection Libraries – Java World Guice Spring Pico Author: Gal Lalouche - Technion 2015 © 4 Our focus today

Guice – Supplier Supplier code (using can be applied to: Constructors Methods All methods annotated Inject will be invoked after the object’s instantiation Fields (not recommended) Author: Gal Lalouche - Technion 2015 © 5 class MyBillingService implements BillingService { private final CreditCardProcessor public MyBillingService(CreditCardProcessor p) { processor = p; } … } That’s it!

Guice – Complex Dependencies Dependencies can also be complex to create: BankAccount may have dependencies of its own TxApprover may be an interface Author: Gal Lalouche - Technion 2015 © 6 class VisaCreditCardProcessor implements CreditCardProcessor { private final BankAccount account; private final TxApprover public VisaCreditCardProcessor(BankAccount a, TxApprover t) { account = a; txApprover = t; } … }

Guice – Module Dependencies are described in a separate Module class: Client code is now: Guice will recursively build the requested binding objects In this case a MyBillingService object will be created with DatabaseTxLog and a VisaProcessor Author: Gal Lalouche - Technion 2015 © 7 public class BillingModule extends AbstractModule protected void configure() { bind(CreditCardProcessor.class).to(VisaCreditCardProcessor.class); bind(TxApprover.class).to(VisaIsraelTxApprover.class); bind(BillingService.class).to(MyBillingService.class); } Injector injector = Guice.createInjector(new BillingModule()); BillingService billingService = injector.getInstance(BillingService.class);

Guice advanced binding Can bind concrete types by: Type Name Annotation Can bind to: A class (new instance every time) An object (a specific instance) Generic classes Author: Gal Lalouche - Technion 2015 © 8

Annotation binding – annotations Binding to annotated class: Persistent TransactionLogs should bind to SqlTxLog Un-persistent TransactionLogs should bind to StringTxLog Author: Gal Lalouche - Technion 2015 © 9 public class BillingModule extends AbstractModule protected void configure() { bind(TransactionLog.class).to(StringTxLog.class); bind(TransactionLog.class).annotatedWith(Persistent.class).to(SqlTxLog.class); } public class PersistentLogger { public TransactionLog l) { this.l = l; }

Binding constants We can use an annotation “shortcut” Bind to specific constant object (instantiated only once) Author: Gal Lalouche - Technion 2015 © 10 class SqlTxLog public URL″) String timeout seconds″) Integer timeout) { … } } public class SqlTxLogModule extends AbstractModule protected void configure() { bind(String.class).annotatedWith(Names.named( " JDBC URL")).toInstance( " jdbc:mysql://localhost/pizza"); bind(Integer.class).annotatedWith(Names.named(″login timeout seconds”)).toInstance(10); }

More on Binding to Instance There are two ways to bind an instance: Using.toInstance passing an instance Using.to(SomeClass.class).in(Singleton.class) A single instance is created by Guice Dependencies are injected according to the Module We can also on the bound class Author: Gal Lalouche - Technion 2015 © 11 bind(String.class).annotatedWith(Names.named("login timeout seconds")).toInstance("10"); bind(BillingService.class).to(MyBillingService.class).in(Singleton.class);

Creational logic If we have some non-trivial creational logic we can write it in method in the Module If this method receives any arguments they will be injected We can also annotate the return type Author: Gal Lalouche - Technion 2015 © 12 public class MyPaymentModule extends AbstractModule protected void configure() { … // will be provided to dependencies annotated TransactionLog URL″) String conURL) { DatabaseTransactionLog transactionLog = new DatabaseTxLog(); transactionLog.setJdbcUrl(connectionURL); transactionLog.setThreadPoolSize(30); return transactionLog; } }

Factories with provider s How do we pass factories? Naïve solution: simply inject an AbstractFactory We have to create a special VisaProcessorFactory class to bind to We bind both to VisaProcessor and VisaProcessorFactory ; that’s not very DRY… Author: Gal Lalouche - Technion 2015 © 13 class MyBillingService implements BillingService public MyBillingService(CreditCardProcessorFactory pf) { this.factory = pf; } }… // module: bind(CreditCardProcessor.class).to(VisaProcessor.class); bind(CreditCardProcessorFactory.class).to(VisaProcessorFactory.class);

Factories with provider s (cont.) Using providers achieves just that! We don’t have to bind the provider explicitly, since we already bound VisaProcessor Food for thought: why don’t we have a problem with type erasure here? This makes the Guice injector instance in essence a FactoryFactory, but it is okay in this case because we don’t need any extra code to support it! Author: Gal Lalouche - Technion 2015 © 14 class MyBillingService implements BillingService public MyBillingService(Provider pf) { this.factory = pf; } }… // module: bind(CreditCardProcessor.class).to(VisaProcessor.class);

Binding Generics Binding generics is a bit complicated due to type erasure Binding classes with generic dependencies: Binding generic classes: Author: Gal Lalouche - Technion 2015 © 15 class A public A(List list) {…} } … bind(new TypeLiteral >(){}).to(new TypeLiteral >(){}); … injector.getInstance(A.class); // A will be injected an ArrayList class B public B(List list) {…} } … bind(new TypeLiteral >(){}).to(new TypeLiteral >(){}); … injector.getInstance(new Key >(){}); // B will be injected an ArrayList

Outcome What we’ve achieved? Both client and supplier are decoupled from implementation details All dependency logic is executed at runtime and is contained in Modules A module encapsulates all creation logic in our program Testing & Mocking is easy – since we’re essentially using constructor injection Side-note: Other DI frameworks (e.g. Spring) use XML files to define dependencies This enables changing the code’s behavior without recompiling But it also has its disadvantages (e.g. it’s not type safe) Author: Gal Lalouche - Technion 2015 © 16

Dependency Injection – Is it really that important? If we want to write real units tests, then we have to isolate our units If we want to isolate our units, then we have to use mocks If we want to use mocks, we have to inject them somehow But we aren’t doing it (just) for the tests! If we use dependency injection, our code is less coupled, more modular, robust, and reusable, cohesive, cleaner and DRYer. Remember, Testable Code => Better Code! Author: Gal Lalouche - Technion 2015 © 17 Unit Tests Mock objects Dependency Injection