Saturday, April 19, 2014

[Spring] Dependency injection

Definition

DI - Dependency Injection
  • A technique in which objects are passively given their dependencies instead of creating or looking for dependent objects for themselves. 
  • [Nattily] DI means how we are going to make sure that all your components are related to one another.
  • [Nattily] same concept IoC.
  • [Nattily] It's a form of push configuration.
  • Based on Hollywood Principle: "Don't call me, I'll call you."


Push configuration


How Non-IoC code looks like


How the code changed with dependency injection



Benefits of Dependency Injection
  • Your object is handed what it needs to work
    • Free your object from the burden of resolving its dependencies.
    • Simplifies your code, improves code reuseability
  • Promotes programming to interfaces
    • Conceals (~hide) the implementation details of each dependency 
    • [Nattily] so that can be performed "Swap out"
  • Remove the responsibility of finding or creating dependent objects and moves it into configuration.
  • Reduces coupling between implementation objects and encourages interface based design.
  • Allows an application to be reconfigured outside of code.
  • Improves testability
    • Dependencies can be easily stubbed out for unit testing 
    • Can encourage writing testable components
  • Allows for centralized control over object lifecycle 
    • Opens the door for new possiblities
Notes:
「保留抽象介面,讓組件依賴於抽象介面,當組件要與其它實際的物件發生依賴關係時,藉過抽象介面來注入依 賴的實際物件。  [link]

Type of Dependency injection

(1) Setter Injection - The injection of dependencies via JavaBean setter methods.
public void setName (String name){
    this.name = name;
}

(2) Constructor Injection - The injection of dependencies via constructor arguments.
public Test (String name){
    this.name = name;
}


sa

No comments:

Post a Comment