Saturday, March 23, 2013

dependency injection

  • Google Guice
Google Guice is an open source software framework for the Java platform released by Google under the Apache License. It provides support for dependency injection using annotations to configure Java objects
Dependency injection is a design pattern whose core principle is to separate behavior from dependency resolution.
http://en.wikipedia.org/wiki/Google_Guice



Put simply, Guice alleviates the need for factories and the use of new in your Java code
Think of Guice's @Inject as the new new
https://code.google.com/p/google-guice/


  • Dependency Injection in Spring
Dependency injection (DI) is a design pattern in object-oriented computer programming whose purpose is to reduce the coupling between software components.
http://www.mkyong.com/spring/spring-dependency-injection-di/
http://en.wikipedia.org/wiki/Dependency_injection
http://www.youtube.com/watch?v=PGfs2CxDGM4



  • You can mix both, Constructor-based and Setter-based DI but it is a good rule of thumb to use constructor arguments for mandatory dependencies and setters for optional dependencies.

ode is cleaner with the DI principle and decoupling is more effective when objects are provided with their dependencies. The object does not look up its dependencies, and does not know the location or class of the dependencies rather everything is taken care by the Spring Framework.

http://www.tutorialspoint.com/spring/spring_dependency_injection.html



  • Dependency Injection Types

Constructor Injection
The constructor arguments are injected during instance instantiation.
Setter Injection
This is the most favored method of dependency injection in Spring. Dependencies are “set” in the objects through setter methods defined in a Spring configuration file
Interface Injection
This is not implemented in Spring currently, but by Avalon. It’s a different type of DI that involves mapping items to inject to specific interfaces.
Spring uses the concept of a BeanFactory as its assembler, and it is the BeanFactory that manages the JavaBeans you have configured to run within it.
In Spring, the initialization of a bean by the framework is exactly equivalent to using the new keyword to instantiate an object in Java code
Once the framework has instantiated the object, it manages the scope of the bean, based on its configuration.

Because the IoC container is managing the beans, JNDI lookups that are typical in Java EE containers are no longer required, leaving your code container-agnostic and easier to unit test both inside and outside of the framework. And while you are coding to interfaces as part of good OO practice, Spring allows you to manage what implementations are used by leveraging dependency injection, resulting in cleaner, decoupled components.

All we need to do is inform Spring through an XML configuration file that the recorder bean is implemented by the LocalVoteRecorder class.
<bean id="recorder"      class="com.springindepth.LocalVoteRecorder" />

Then we simply map the recorder bean to the VotingBooth bean by setter injection in that beans definition.
<bean id="votingBooth"
      class="com.springindepth.VotingBooth">
    <property name="voteRecorder" ref="recorder"/>
</bean>

The IoC container manages java objects – from instantiation to destruction – through its BeanFactory.

http://www.springbyexample.org/examples/core-concepts-bean-management-through-ioc.html



  • Basic Bean Creation

A Spring bean in the IoC container can typically be any POJO (plain old java object).
Creating a Spring bean is as simple as coding your POJO and adding a bean configuration element to the Spring XML configuration file or annotating the POJO

             
public class DefaultMessage {

    private String message = "Spring is fun.";

    /**
    * Gets message.
    */
    public String getMessage() {
        return message;
    }

    /**
    * Sets message.
    */
    public void setMessage(String message) {
        this.message = message;
    }

}


  The bean element below indicates a bean of type Message – defined by the class attribute – with an id of 'message'.
  The instance of this bean will be registered in the container with this id.
  <bean id="message"    class="org.springbyexample.di.xml.DefaultMessage" />

  When the container instantiates the message bean, it is equivalent to initializing an object in your code with 'new DefaultMessage()'.


http://www.springbyexample.org/examples/intro-to-ioc.html



  • Basic Constructor Injection

we have our POJO and a basic configuration for the message bean, we can introduce our first dependency injection examples
Through the Spring beans XML file you can configure your bean to initialize with an argument for the constructor, and then assign the arguments.
Spring essentially “injects” the argument into your beans
This is referred to as constructor injection.

The following example passes in the String message using a constructor. The class is the same as the one in Basic Bean Creation except the default message on the message variable has been cleared and is now set to null. A single parameter constructor has been added to set a message.

public class ConstructorMessage {

    private String message = null;

    /**
    * Constructor
    */
    public ConstructorMessage(String message) {
        this.message = message;
    }

    /**
    * Gets message.
    */
    public String getMessage() {
        return message;
    }

    /**
    * Sets message.
    */
    public void setMessage(String message) {
        this.message = message;
    }

}


The configuration for this bean is exactly the same as in the previous example, but now we have a new element, the constructor-arg. The constructor-arg element injects a message into the bean using the constructor-arg element's value attribute.

<bean id="message"  class="org.springbyexample.di.xml.ConstructorMessage">
        <constructor-arg value="Spring is fun." />
    </bean>



http://www.springbyexample.org/examples/intro-to-ioc-basic-constructor-injection.html


  • Basic Setter Injection

The Spring IoC container also supports setter injection, which is the preferred method of dependency injection in Spring.

In most cases Spring will lowercase the first letter after “set” in the method name and use the rest of the method name as-is for deducing the property name. So for example if there is a setMessage() method in your class, the property name you would use when setting that property on a bean in the XML config is 'message'. If there is a setFirstName() method in your class, the property name you would use when setting the value is 'firstName'. 
In cases where the letters after “set” are all uppercase, Spring will leave the property name as uppercase. So if you have setXML() on a class, the property name would be 'XML'

public class SetterMessage {

    private String message = null;

    /**
    * Gets message.
    */
    public String getMessage() {
        return message;
    }

    /**
    * Sets message.
    */
    public void setMessage(String message) {
        this.message = message;
    }

}
  
  
  The property element is used to define the setter injection: 
  
  <bean id="message" class="org.springbyexample.di.xml.SetterMessage">
        <property name="message" value="Spring is fun." />
    </bean>

http://www.springbyexample.org/examples/intro-to-ioc-basic-setter-injection.html


  • Reference Injection
Values can also be injected by reference 
one bean definition can be injected into another.
To do this, you use the constructor-arg or property's ref attribute instead of the value attribute

  the first bean definition is a java.lang.String with the id springMessage
  
  <bean id="springMessage" class="java.lang.String">
        <constructor-arg value="Spring is fun." />
  </bean>
  
  
  It is injected into the second bean definition by reference using the property element's ref attribute.
  
  <bean id="message"  class="org.springbyexample.di.xml.SetterMessage">
        <property name="message" ref="springMessage" />
  </bean>
  
  http://www.springbyexample.org/examples/intro-to-ioc-reference-injection.html


  •   Spring Constructor-based Dependency Injection
  
  Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.
  
  
package com.tutorialspoint;

public class SpellChecker {
  public SpellChecker(){
      System.out.println("Inside SpellChecker constructor." );
  }

  public void checkSpelling() {
      System.out.println("Inside checkSpelling." );
  }
  
}

<!-- Definition for spellChecker bean -->
<bean id="spellChecker" class="com.tutorialspoint.SpellChecker"></bean>



package com.tutorialspoint;

public class TextEditor {
  private SpellChecker spellChecker;

  public TextEditor(SpellChecker spellChecker) {
      System.out.println("Inside TextEditor constructor." );
      this.spellChecker = spellChecker;
  }
  public void spellCheck() {
      spellChecker.checkSpelling();
  }
}


<!-- Definition for textEditor bean -->
  <bean id="textEditor" class="com.tutorialspoint.TextEditor">
      <constructor-arg ref="spellChecker"/>
  </bean>
  
  
  To resolve this ambiguity, the order in which the constructor arguments are defined in a bean definition is the order in which those arguments are supplied to the appropriate constructor_based_dependency_injection
  
package x.y;

public class Foo {
  public Foo(int year, String name) {
      // ...
  }
}
  

  <beans>
  <bean id="foo" class="x.y.Foo">
      <constructor-arg ref="bar"/>
      <constructor-arg ref="baz"/>
  </bean>

  <bean id="bar" class="x.y.Bar"/>
  <bean id="baz" class="x.y.Baz"/>
</beans> 
  
  
  one more case where we pass different types to the constructor_based_dependency_injection
  
  package x.y;

    public class Foo {
      public Foo(int year, String name) {
      // ...
      }
    }

    
    <bean id="exampleBean" class="examples.ExampleBean">
      <constructor-arg type="int" value="2001"/>
      <constructor-arg type="java.lang.String" value="Zara"/>
  </bean>
  
  
  the best way to pass constructor arguments, use the index attribute to specify explicitly the index of constructor arguments
  
  <bean id="exampleBean" class="examples.ExampleBean">
      <constructor-arg index="0" value="2001"/>
      <constructor-arg index="1" value="Zara"/>
  </bean>
  
  in case you are passing a reference to an object, you need to use ref attribute of <constructor-arg> tag and if you are passing a value directly then you should use value attribute
  
  
http://www.tutorialspoint.com/spring/constructor_based_dependency_injection.htm

Spring can instance objects in two ways: 

    Singleton: Instantiate only one object
    Prototype: Instantiate a new object everytime

        <bean id="ticketVendingMachine"
        class="com.studytrails.tutorials.springsingletonandprototype.TicketVendingMachine"
        scope="singleton" />

    <bean id="ticket"
        class="com.studytrails.tutorials.springsingletonandprototype.Ticket"
        scope="prototype" />
        
        
    http://www.studytrails.com/frameworks/spring/spring-singleton-and-prototype.jsp


  •     Spring Dependency Injection: Setter Injection
    
    
    the ATM class and Printer class can collaborate with each other to print the balance information for a bank account
    
    dependency where the reference of one class is held by another class
    
    The ATM class holds a reference to Printer class below. 
    
    private Printer printer;
    
    ATM class depends on Printer class
    
    public class ATM { 
    private Printer printer;
    
    
    The dependencies need to be 'resolved' before the desired functionality can be achieved
    By 'resolved' we mean that an instance of Printer class needs to be created and associated with the 'printer' member in ATM class
    When dependency resolution is not performed by the class itself but is left to be done by an external agent (e.g. Spring Framework) it is called dependency injection
    Spring will create an instance of the Printer class and associate the instance with the 'printer' member in ATM class
    as the 'printer' member in ATM class is private, the ATM class needs to expose its dependency to Spring for it to inject the Printer instance into the ATM class.
    
    If the ATM class exposes its dependency on Printer class as a setter method so that Spring can inject the Printer object then this is called as Setter injection
    
    public void setPrinter(Printer printer)
    
    ATM class takes in Printer class as a setter methods
    
    public class ATM {

    private Printer printer;

    public Printer getPrinter() {
        return printer;
    }
    public void setPrinter(Printer printer) {
        this.printer = printer;
    }
    
    
       
    
    http://www.studytrails.com/frameworks/spring/spring-setter-injection.jsp


  •  Spring Dependency Injection: Constructor Injection
    
    Spring will create an instance of the Printer class and associate the instance with the 'printer' member in ATM class. 
    as the 'printer' member in ATM class is private, the ATM class needs to expose its dependency to Spring for it to inject the Printer instance into the ATM class
    
    If the ATM class exposes its dependency on Printer class as a constructor so that Spring can inject it then this is called as Constructor injection
    
    public ATM(Printer printer) 
    
    ATM class takes in Printer class as a constructor argument 
    
    public class ATM {

    private Printer printer;
    
    public ATM(Printer printer) {
        this.printer = printer;
    }
    ...
    
    
    <bean id="printer" class="com.studytrails.tutorials.springcontructorinjection.Printer">
    </bean>
    
    <bean id="atm" class="com.studytrails.tutorials.springcontructorinjection.ATM">
            <constructor-arg ref="printer"/>
    </bean>    
        
    
    
    http://www.studytrails.com/frameworks/spring/spring-constructor-injection.jsp


  • IOC can be achieved by either of the following:
1. DI (Dependency Injection)
2. Service Locator


3 types of DI
1.1 Constructor Injection
1.2 Setter Injection
1.3 Interface Injection

http://programmers.stackexchange.com/questions/131451/difference-between-dependency-injection-di-inversion-of-control-ioc


  • Inversion of Control vs Dependency Injection [closed]
inversion of control is the principle where the control flow of a program is inverted: instead the programmer controls the flow of a program, the external sources (framework, services, other components) take control of it. It likes we plug something into something else

IoC is a generic term meaning rather than having the application call the methods in a framework, the framework calls implementations provided by the application.
DI is a form of IoC, where implementations are passed into an object through constructors/setters/service look-ups, which the object will 'depend' on in order to behave correctly.

IoC without using DI, for example would be the Template pattern because the implementation can only be changed through sub-classing.

DI Frameworks are designed to make use of DI and can define interfaces (or Annotations in Java) to make it easy to pass in implementations.

IoC Containers are DI frameworks that can work outside of the programming language. In some you can configure which implementations to use in metadata files (e.g. XML) which are less invasive. With some you can do IoC that would normally be impossible like inject implementation at pointcuts.

Inversion of Control (IoC) means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside source (for example, an xml configuration file).

Dependency Injection (DI) means that this is done without the object intervention, usually by a framework component that passes constructor parameters and set properties.


http://stackoverflow.com/questions/6550700/inversion-of-control-vs-dependency-injection

No comments:

Post a Comment