<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Whiteopal</id>
	<title>Expertiza_Wiki - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Whiteopal"/>
	<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=Special:Contributions/Whiteopal"/>
	<updated>2026-05-17T18:46:38Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.41.0</generator>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=40036</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=40036"/>
		<updated>2010-11-03T23:55:47Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: /* Advantages and Disadvantages */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability.[http://www.codeproject.com/KB/architecture/DependencyInjection.aspx] This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
== Definition ==&lt;br /&gt;
The basic concept of Dependency Injection(DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class.[http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators]&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control(IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
== Features of Dependency Injection ==&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
* More Testable- It makes it very easy to test the code, as objects get instantiated with values using configuration files.&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.[http://www.springsource.org/]&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is a highly effective command pattern framework that provides a lot of features for DI.[http://www.opensymphony.com/xwork/]&lt;br /&gt;
* '''Apache Avalon'''- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.[http://excalibur.apache.org/framework/index.html]&lt;br /&gt;
* '''PicoContainer''' - It is a highly focused DI framework available.[http://www.picocontainer.org/]&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.[http://hivelogic.com/]&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us consider a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object. We need some Assembler (DI Framework) to instantiate the Department field of Employee class. Rather than Employee class creating this object for itself, it will delegate this task of instantiation to any framework selected from above. To do this, it uses configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Types_of_Dependency_Injection section 3]. &lt;br /&gt;
&lt;br /&gt;
 '''''Employee.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( ){ }  &lt;br /&gt;
         &lt;br /&gt;
         setDepartment(dept){&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
         }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''Department.java'''''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName(){&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name){&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
The framework will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object. It will form an Employee object with a Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where the binding of beans is done as follows:&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
      &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
      &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	   &amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, one only needs to update the configuration file. There is no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is a technique to add the dependency for interfaces in components at run time. The components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using the Avalon framework.&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 '''''AccountApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
 {&lt;br /&gt;
        void getEntity(){&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
        }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''CustomerApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
 {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
        {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
        }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface. The ApplicationServiceImpl class implements the ApplicationService inteface, which in turn implements the ApplicationDAO interface, provided by the container.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
 {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationServiceImpl.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
  {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
         {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
          }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container, which uses configuration file for look up, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
            string implementClass =  &lt;br /&gt;
                                    System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
            ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
             &lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
The Configuration File that will be used by MyClass file to lookup the dependency configurations will be of type:&lt;br /&gt;
&lt;br /&gt;
 '''''App.Config'''''&lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
      &amp;lt;appSettings&amp;gt;&lt;br /&gt;
            &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
       &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
In this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference. The getEntity() that is invoked will actually depend on the dependency that is injected via the configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state(variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us consider an example of Setter injection by using Spring Framework.[3] Before using Spring, let us study some basic features of Spring. We will cover only a brief overview of the Spring Framework. &lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[http://static.springsource.org/spring/docs/2.5.x/reference/aop.html], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
Now let us see Setter injection using the Spring framework.&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is the class on which DoctorService depends. &amp;lt;br&amp;gt;[[image:di_image2.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
       { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
       }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
       { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
       }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
       {&lt;br /&gt;
              System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
              System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
       }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
        private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
                return  this.prescription;&lt;br /&gt;
        }&lt;br /&gt;
        public void setPrescription(String prescription) &lt;br /&gt;
        {&lt;br /&gt;
           this. prescription = prescription;&lt;br /&gt;
        }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
Here, the invoking object is responsible for setting the PrescriptionDAO dependency. There is no code inside the class that is creating new instance of PrescriptionDAO. This is because this task will be performed by the Spring container, by looking for dependencies of DoctorService inside applicationContext.xml file.&lt;br /&gt;
&lt;br /&gt;
The Spring framework uses a setter method to create this dependent object. Note the &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
       &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
                  &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
                  &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
       &amp;lt;/bean&amp;gt;&lt;br /&gt;
       &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
                 &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
                 &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
       &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions from inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
 public class MyClient&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(String args[])&lt;br /&gt;
        {&lt;br /&gt;
                Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
                BeanFactory factory =new XmlBeanFactory(res); &lt;br /&gt;
                //” doctorServiceId” is the same id defined in ApplicationContext.xml&lt;br /&gt;
                DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
         }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first the path for the ApplicationContext is specified, and then this file is used as a resource by the container. The BeanFactory container uses the xml file to access the bean defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However, Setter Injection unnecessarily adds to the abstraction. The developer needs to know which dependencies are needed when. On the other hand, it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;br /&gt;
&lt;br /&gt;
==Type 3- Constructor Injection==&lt;br /&gt;
&lt;br /&gt;
Constructor Injection is the DI technique of passing an object's dependencies to its constructor. It addresses the most common scenario where a class requires one or more Dependencies, and no reasonable local defaults are available.&lt;br /&gt;
&lt;br /&gt;
Constructor Injection addresses this scenario very well, because it guarantees that the Dependency is always present. If the depending class absolutely cannot function without the Dependency, such a guarantee is valuable. Constructor-injection enforces the order of initialization and prevents circular dependencies [http://en.wikipedia.org/wiki/Circular_dependency]. &lt;br /&gt;
On the other hand, with Setter injection, it is not clear, in which order things need to be instantiated. Apart from the guaranteed injection, this pattern is also very easy to implement. &lt;br /&gt;
&lt;br /&gt;
Continuing with the example mentioned above, we can implement the same using constructor injection as follows, &amp;lt;br&amp;gt; [[image:di_image3.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
         private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
         // constructor for instantiatng prescriptionDAO&lt;br /&gt;
         public DoctorService (prescriptionDAO)&lt;br /&gt;
         { &lt;br /&gt;
            this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
         }&lt;br /&gt;
         //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
          public void print()&lt;br /&gt;
          {	&lt;br /&gt;
               System.out.println(&amp;quot;prescription:&amp;quot; +prescriptionDAO.prescription);&lt;br /&gt;
               System.out.println(&amp;quot;dose: &amp;quot;+prescriptionDAO.dose); &lt;br /&gt;
          }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
In the example, you must have noticed the parametrized constructor which Spring framework uses to instantiate the value of prescriptionDAO. &lt;br /&gt;
Now, the question is- how Spring container will come to know whether it has to use Constructor injection or Setter Injection? Tags inside the &amp;lt;bean&amp;gt; tag will specify this:&lt;br /&gt;
* &amp;lt;property&amp;gt; tag   is used for Setter Injection&lt;br /&gt;
* &amp;lt;constructor-arg&amp;gt; is used for Constructor Injection.&lt;br /&gt;
&lt;br /&gt;
ApplicationContect.xml for Constructor injection will be:&lt;br /&gt;
 '''''ApplicationContect.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
                 &amp;lt;!-- constructor injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
 		 &amp;lt;constructor-arg&amp;gt;&lt;br /&gt;
                 &amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&lt;br /&gt;
                 &amp;lt;/constructor-arg&amp;gt;&lt;br /&gt;
          &amp;lt;/bean&amp;gt;&lt;br /&gt;
          &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
                 &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
                 &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
          &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Definitions for PrescriptionDAO.java and MyClient.java will remain the same.&lt;br /&gt;
The advantage of using Constructor Injection is that it can create the objects at the time of instantiation itself. Hence it guarantees the developer, that the objects will definitely get created and no exception will be raised. &lt;br /&gt;
&lt;br /&gt;
However, unlike [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Type_2-_Setter_Injection Setter injection] it won’t allow changes to the dependency, once it is created.&lt;br /&gt;
&lt;br /&gt;
=Advantages and Disadvantages=&lt;br /&gt;
&lt;br /&gt;
Advantage of using Dependency injection are &lt;br /&gt;
* Clean code which helps to separate out the logic and the instantiation modules. &lt;br /&gt;
* It is also easy to maintain the code with the use of configuration files where we can make changes in future whenever required. &lt;br /&gt;
* It is very easy to test the code using Dependency Injection.&lt;br /&gt;
* It makes the code more readable.&lt;br /&gt;
&lt;br /&gt;
Disadvantages are &lt;br /&gt;
* A developer cannot understand the code easily as there is an abstraction layer which performs the initializing and instantiation of objects. &lt;br /&gt;
* Developers need to have a certain level of expertise in coding such design patterns.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
[1] [http://www.amazon.com/Spring-Action-Craig-Walls/dp/1932394354 Walls, C.,Briedenbach, R. ''Spring in Action'' Manning]&amp;lt;br&amp;gt;&lt;br /&gt;
[2] [http://www.amazon.com/Professional-Java-Development-Spring-Framework/dp/0764574833 Johnson, R., Hoeller, J., Arendsen, A. ''Professional Java Development with Spring Framework'' Wrox]&amp;lt;br&amp;gt;&lt;br /&gt;
[3] [http://www.springsource.org/ Spring Framework]&amp;lt;br&amp;gt;&lt;br /&gt;
[4] [http://www.opensymphony.com/xwork/ Xwork]&amp;lt;br&amp;gt;&lt;br /&gt;
[5] [http://static.springsource.org/spring/docs/2.5.x/reference/aop.html Aspect Oriented Programming]&amp;lt;br&amp;gt;&lt;br /&gt;
[6] [http://en.wikipedia.org/wiki/Circular_dependency Circular Dependency]&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=External Links=&lt;br /&gt;
[1] [http://www.codeproject.com/KB/architecture/DependencyInjection.aspx Dependency Injection for Loose Coupling]&amp;lt;br&amp;gt;&lt;br /&gt;
[2] [http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators Dependency injection]&amp;lt;br&amp;gt;&lt;br /&gt;
[3] [http://excalibur.apache.org/framework/index.html Excalibur Apache Avalon]&amp;lt;br&amp;gt;&lt;br /&gt;
[4] [http://www.picocontainer.org/ PicoContainer]&amp;lt;br&amp;gt;&lt;br /&gt;
[5] [http://hivelogic.com/ Hivelogic]&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
[1] [http://www.manning.com/seemann/ Seemann, M. ''Dependency Injection in .NET'' Manning]&amp;lt;br&amp;gt;&lt;br /&gt;
[2] [http://www.manning.com/prasanna/ Prassanna, D. ''Dependency Injection'' Manning]&amp;lt;br&amp;gt;&lt;br /&gt;
[3] [http://www.developer.com/net/csharp/article.php/3722931/Dependency-Injection-with-SpringNet.htm Dependency Injection with Spring .NET] &amp;lt;br&amp;gt;&lt;br /&gt;
[4] [http://needle.rubyforge.org/api/ Dependency Injection in Ruby]&lt;br /&gt;
[5] [http://onestepback.org/index.cgi/Tech/Ruby/DependencyInjectionInRuby.rdoc ]&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=40035</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=40035"/>
		<updated>2010-11-03T23:50:53Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: /* Conclusion */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability.[http://www.codeproject.com/KB/architecture/DependencyInjection.aspx] This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
== Definition ==&lt;br /&gt;
The basic concept of Dependency Injection(DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class.[http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators]&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control(IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
== Features of Dependency Injection ==&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
* More Testable- It makes it very easy to test the code, as objects get instantiated with values using configuration files.&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.[http://www.springsource.org/]&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is a highly effective command pattern framework that provides a lot of features for DI.[http://www.opensymphony.com/xwork/]&lt;br /&gt;
* '''Apache Avalon'''- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.[http://excalibur.apache.org/framework/index.html]&lt;br /&gt;
* '''PicoContainer''' - It is a highly focused DI framework available.[http://www.picocontainer.org/]&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.[http://hivelogic.com/]&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us consider a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object. We need some Assembler (DI Framework) to instantiate the Department field of Employee class. Rather than Employee class creating this object for itself, it will delegate this task of instantiation to any framework selected from above. To do this, it uses configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Types_of_Dependency_Injection section 3]. &lt;br /&gt;
&lt;br /&gt;
 '''''Employee.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( ){ }  &lt;br /&gt;
         &lt;br /&gt;
         setDepartment(dept){&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
         }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''Department.java'''''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName(){&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name){&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
The framework will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object. It will form an Employee object with a Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where the binding of beans is done as follows:&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
      &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
      &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	   &amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, one only needs to update the configuration file. There is no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is a technique to add the dependency for interfaces in components at run time. The components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using the Avalon framework.&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 '''''AccountApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
 {&lt;br /&gt;
        void getEntity(){&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
        }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''CustomerApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
 {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
        {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
        }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface. The ApplicationServiceImpl class implements the ApplicationService inteface, which in turn implements the ApplicationDAO interface, provided by the container.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
 {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationServiceImpl.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
  {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
         {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
          }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container, which uses configuration file for look up, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
            string implementClass =  &lt;br /&gt;
                                    System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
            ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
             &lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
The Configuration File that will be used by MyClass file to lookup the dependency configurations will be of type:&lt;br /&gt;
&lt;br /&gt;
 '''''App.Config'''''&lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
      &amp;lt;appSettings&amp;gt;&lt;br /&gt;
            &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
       &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
In this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference. The getEntity() that is invoked will actually depend on the dependency that is injected via the configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state(variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us consider an example of Setter injection by using Spring Framework.[3] Before using Spring, let us study some basic features of Spring. We will cover only a brief overview of the Spring Framework. &lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[http://static.springsource.org/spring/docs/2.5.x/reference/aop.html], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
Now let us see Setter injection using the Spring framework.&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is the class on which DoctorService depends. &amp;lt;br&amp;gt;[[image:di_image2.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
       { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
       }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
       { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
       }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
       {&lt;br /&gt;
              System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
              System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
       }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
        private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
                return  this.prescription;&lt;br /&gt;
        }&lt;br /&gt;
        public void setPrescription(String prescription) &lt;br /&gt;
        {&lt;br /&gt;
           this. prescription = prescription;&lt;br /&gt;
        }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
Here, the invoking object is responsible for setting the PrescriptionDAO dependency. There is no code inside the class that is creating new instance of PrescriptionDAO. This is because this task will be performed by the Spring container, by looking for dependencies of DoctorService inside applicationContext.xml file.&lt;br /&gt;
&lt;br /&gt;
The Spring framework uses a setter method to create this dependent object. Note the &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
       &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
                  &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
                  &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
       &amp;lt;/bean&amp;gt;&lt;br /&gt;
       &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
                 &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
                 &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
       &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions from inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
 public class MyClient&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(String args[])&lt;br /&gt;
        {&lt;br /&gt;
                Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
                BeanFactory factory =new XmlBeanFactory(res); &lt;br /&gt;
                //” doctorServiceId” is the same id defined in ApplicationContext.xml&lt;br /&gt;
                DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
         }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first the path for the ApplicationContext is specified, and then this file is used as a resource by the container. The BeanFactory container uses the xml file to access the bean defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However, Setter Injection unnecessarily adds to the abstraction. The developer needs to know which dependencies are needed when. On the other hand, it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;br /&gt;
&lt;br /&gt;
==Type 3- Constructor Injection==&lt;br /&gt;
&lt;br /&gt;
Constructor Injection is the DI technique of passing an object's dependencies to its constructor. It addresses the most common scenario where a class requires one or more Dependencies, and no reasonable local defaults are available.&lt;br /&gt;
&lt;br /&gt;
Constructor Injection addresses this scenario very well, because it guarantees that the Dependency is always present. If the depending class absolutely cannot function without the Dependency, such a guarantee is valuable. Constructor-injection enforces the order of initialization and prevents circular dependencies [http://en.wikipedia.org/wiki/Circular_dependency]. &lt;br /&gt;
On the other hand, with Setter injection, it is not clear, in which order things need to be instantiated. Apart from the guaranteed injection, this pattern is also very easy to implement. &lt;br /&gt;
&lt;br /&gt;
Continuing with the example mentioned above, we can implement the same using constructor injection as follows, &amp;lt;br&amp;gt; [[image:di_image3.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
         private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
         // constructor for instantiatng prescriptionDAO&lt;br /&gt;
         public DoctorService (prescriptionDAO)&lt;br /&gt;
         { &lt;br /&gt;
            this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
         }&lt;br /&gt;
         //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
          public void print()&lt;br /&gt;
          {	&lt;br /&gt;
               System.out.println(&amp;quot;prescription:&amp;quot; +prescriptionDAO.prescription);&lt;br /&gt;
               System.out.println(&amp;quot;dose: &amp;quot;+prescriptionDAO.dose); &lt;br /&gt;
          }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
In the example, you must have noticed the parametrized constructor which Spring framework uses to instantiate the value of prescriptionDAO. &lt;br /&gt;
Now, the question is- how Spring container will come to know whether it has to use Constructor injection or Setter Injection? Tags inside the &amp;lt;bean&amp;gt; tag will specify this:&lt;br /&gt;
* &amp;lt;property&amp;gt; tag   is used for Setter Injection&lt;br /&gt;
* &amp;lt;constructor-arg&amp;gt; is used for Constructor Injection.&lt;br /&gt;
&lt;br /&gt;
ApplicationContect.xml for Constructor injection will be:&lt;br /&gt;
 '''''ApplicationContect.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
                 &amp;lt;!-- constructor injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
 		 &amp;lt;constructor-arg&amp;gt;&lt;br /&gt;
                 &amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&lt;br /&gt;
                 &amp;lt;/constructor-arg&amp;gt;&lt;br /&gt;
          &amp;lt;/bean&amp;gt;&lt;br /&gt;
          &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
                 &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
                 &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
          &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Definitions for PrescriptionDAO.java and MyClient.java will remain the same.&lt;br /&gt;
The advantage of using Constructor Injection is that it can create the objects at the time of instantiation itself. Hence it guarantees the developer, that the objects will definitely get created and no exception will be raised. &lt;br /&gt;
&lt;br /&gt;
However, unlike [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Type_2-_Setter_Injection Setter injection] it won’t allow changes to the dependency, once it is created.&lt;br /&gt;
&lt;br /&gt;
=Advantages and Disadvantages=&lt;br /&gt;
&lt;br /&gt;
Advantage of using Dependency injection are &lt;br /&gt;
* Clean code which helps to separate out the logic and the instantiation modules. &lt;br /&gt;
* It is also easy to maintain the code with the use of configuration files where we can make changes in future whenever required. &lt;br /&gt;
* It is very easy to test the code using Dependency Injection.&lt;br /&gt;
* It makes the code more readable.&lt;br /&gt;
&lt;br /&gt;
Disadvantages are &lt;br /&gt;
* A developer cannot understand the code easily as there is an abstraction layer which is performing initializing and instantiation of objects. &lt;br /&gt;
* Developers need to have a certain level of expertise in coding such design patterns.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
[1] [http://www.amazon.com/Spring-Action-Craig-Walls/dp/1932394354 Walls, C.,Briedenbach, R. ''Spring in Action'' Manning]&amp;lt;br&amp;gt;&lt;br /&gt;
[2] [http://www.amazon.com/Professional-Java-Development-Spring-Framework/dp/0764574833 Johnson, R., Hoeller, J., Arendsen, A. ''Professional Java Development with Spring Framework'' Wrox]&amp;lt;br&amp;gt;&lt;br /&gt;
[3] [http://www.springsource.org/ Spring Framework]&amp;lt;br&amp;gt;&lt;br /&gt;
[4] [http://www.opensymphony.com/xwork/ Xwork]&amp;lt;br&amp;gt;&lt;br /&gt;
[5] [http://static.springsource.org/spring/docs/2.5.x/reference/aop.html Aspect Oriented Programming]&amp;lt;br&amp;gt;&lt;br /&gt;
[6] [http://en.wikipedia.org/wiki/Circular_dependency Circular Dependency]&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=External Links=&lt;br /&gt;
[1] [http://www.codeproject.com/KB/architecture/DependencyInjection.aspx Dependency Injection for Loose Coupling]&amp;lt;br&amp;gt;&lt;br /&gt;
[2] [http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators Dependency injection]&amp;lt;br&amp;gt;&lt;br /&gt;
[3] [http://excalibur.apache.org/framework/index.html Excalibur Apache Avalon]&amp;lt;br&amp;gt;&lt;br /&gt;
[4] [http://www.picocontainer.org/ PicoContainer]&amp;lt;br&amp;gt;&lt;br /&gt;
[5] [http://hivelogic.com/ Hivelogic]&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
[1] [http://www.manning.com/seemann/ Seemann, M. ''Dependency Injection in .NET'' Manning]&amp;lt;br&amp;gt;&lt;br /&gt;
[2] [http://www.manning.com/prasanna/ Prassanna, D. ''Dependency Injection'' Manning]&amp;lt;br&amp;gt;&lt;br /&gt;
[3] [http://www.developer.com/net/csharp/article.php/3722931/Dependency-Injection-with-SpringNet.htm Dependency Injection with Spring .NET] &amp;lt;br&amp;gt;&lt;br /&gt;
[4] [http://needle.rubyforge.org/api/ Dependency Injection in Ruby]&lt;br /&gt;
[5] [http://onestepback.org/index.cgi/Tech/Ruby/DependencyInjectionInRuby.rdoc ]&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=40034</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=40034"/>
		<updated>2010-11-03T23:49:52Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: /* Advantages and Disadvantages */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability.[http://www.codeproject.com/KB/architecture/DependencyInjection.aspx] This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
== Definition ==&lt;br /&gt;
The basic concept of Dependency Injection(DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class.[http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators]&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control(IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
== Features of Dependency Injection ==&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
* More Testable- It makes it very easy to test the code, as objects get instantiated with values using configuration files.&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.[http://www.springsource.org/]&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is a highly effective command pattern framework that provides a lot of features for DI.[http://www.opensymphony.com/xwork/]&lt;br /&gt;
* '''Apache Avalon'''- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.[http://excalibur.apache.org/framework/index.html]&lt;br /&gt;
* '''PicoContainer''' - It is a highly focused DI framework available.[http://www.picocontainer.org/]&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.[http://hivelogic.com/]&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us consider a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object. We need some Assembler (DI Framework) to instantiate the Department field of Employee class. Rather than Employee class creating this object for itself, it will delegate this task of instantiation to any framework selected from above. To do this, it uses configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Types_of_Dependency_Injection section 3]. &lt;br /&gt;
&lt;br /&gt;
 '''''Employee.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( ){ }  &lt;br /&gt;
         &lt;br /&gt;
         setDepartment(dept){&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
         }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''Department.java'''''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName(){&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name){&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
The framework will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object. It will form an Employee object with a Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where the binding of beans is done as follows:&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
      &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
      &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	   &amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, one only needs to update the configuration file. There is no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is a technique to add the dependency for interfaces in components at run time. The components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using the Avalon framework.&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 '''''AccountApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
 {&lt;br /&gt;
        void getEntity(){&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
        }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''CustomerApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
 {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
        {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
        }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface. The ApplicationServiceImpl class implements the ApplicationService inteface, which in turn implements the ApplicationDAO interface, provided by the container.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
 {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationServiceImpl.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
  {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
         {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
          }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container, which uses configuration file for look up, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
            string implementClass =  &lt;br /&gt;
                                    System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
            ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
             &lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
The Configuration File that will be used by MyClass file to lookup the dependency configurations will be of type:&lt;br /&gt;
&lt;br /&gt;
 '''''App.Config'''''&lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
      &amp;lt;appSettings&amp;gt;&lt;br /&gt;
            &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
       &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
In this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference. The getEntity() that is invoked will actually depend on the dependency that is injected via the configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state(variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us consider an example of Setter injection by using Spring Framework.[3] Before using Spring, let us study some basic features of Spring. We will cover only a brief overview of the Spring Framework. &lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[http://static.springsource.org/spring/docs/2.5.x/reference/aop.html], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
Now let us see Setter injection using the Spring framework.&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is the class on which DoctorService depends. &amp;lt;br&amp;gt;[[image:di_image2.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
       { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
       }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
       { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
       }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
       {&lt;br /&gt;
              System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
              System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
       }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
        private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
                return  this.prescription;&lt;br /&gt;
        }&lt;br /&gt;
        public void setPrescription(String prescription) &lt;br /&gt;
        {&lt;br /&gt;
           this. prescription = prescription;&lt;br /&gt;
        }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
Here, the invoking object is responsible for setting the PrescriptionDAO dependency. There is no code inside the class that is creating new instance of PrescriptionDAO. This is because this task will be performed by the Spring container, by looking for dependencies of DoctorService inside applicationContext.xml file.&lt;br /&gt;
&lt;br /&gt;
The Spring framework uses a setter method to create this dependent object. Note the &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
       &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
                  &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
                  &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
       &amp;lt;/bean&amp;gt;&lt;br /&gt;
       &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
                 &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
                 &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
       &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions from inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
 public class MyClient&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(String args[])&lt;br /&gt;
        {&lt;br /&gt;
                Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
                BeanFactory factory =new XmlBeanFactory(res); &lt;br /&gt;
                //” doctorServiceId” is the same id defined in ApplicationContext.xml&lt;br /&gt;
                DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
         }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first the path for the ApplicationContext is specified, and then this file is used as a resource by the container. The BeanFactory container uses the xml file to access the bean defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However, Setter Injection unnecessarily adds to the abstraction. The developer needs to know which dependencies are needed when. On the other hand, it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;br /&gt;
&lt;br /&gt;
==Type 3- Constructor Injection==&lt;br /&gt;
&lt;br /&gt;
Constructor Injection is the DI technique of passing an object's dependencies to its constructor. It addresses the most common scenario where a class requires one or more Dependencies, and no reasonable local defaults are available.&lt;br /&gt;
&lt;br /&gt;
Constructor Injection addresses this scenario very well, because it guarantees that the Dependency is always present. If the depending class absolutely cannot function without the Dependency, such a guarantee is valuable. Constructor-injection enforces the order of initialization and prevents circular dependencies [http://en.wikipedia.org/wiki/Circular_dependency]. &lt;br /&gt;
On the other hand, with Setter injection, it is not clear, in which order things need to be instantiated. Apart from the guaranteed injection, this pattern is also very easy to implement. &lt;br /&gt;
&lt;br /&gt;
Continuing with the example mentioned above, we can implement the same using constructor injection as follows, &amp;lt;br&amp;gt; [[image:di_image3.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
         private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
         // constructor for instantiatng prescriptionDAO&lt;br /&gt;
         public DoctorService (prescriptionDAO)&lt;br /&gt;
         { &lt;br /&gt;
            this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
         }&lt;br /&gt;
         //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
          public void print()&lt;br /&gt;
          {	&lt;br /&gt;
               System.out.println(&amp;quot;prescription:&amp;quot; +prescriptionDAO.prescription);&lt;br /&gt;
               System.out.println(&amp;quot;dose: &amp;quot;+prescriptionDAO.dose); &lt;br /&gt;
          }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
In the example, you must have noticed the parametrized constructor which Spring framework uses to instantiate the value of prescriptionDAO. &lt;br /&gt;
Now, the question is- how Spring container will come to know whether it has to use Constructor injection or Setter Injection? Tags inside the &amp;lt;bean&amp;gt; tag will specify this:&lt;br /&gt;
* &amp;lt;property&amp;gt; tag   is used for Setter Injection&lt;br /&gt;
* &amp;lt;constructor-arg&amp;gt; is used for Constructor Injection.&lt;br /&gt;
&lt;br /&gt;
ApplicationContect.xml for Constructor injection will be:&lt;br /&gt;
 '''''ApplicationContect.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
                 &amp;lt;!-- constructor injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
 		 &amp;lt;constructor-arg&amp;gt;&lt;br /&gt;
                 &amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&lt;br /&gt;
                 &amp;lt;/constructor-arg&amp;gt;&lt;br /&gt;
          &amp;lt;/bean&amp;gt;&lt;br /&gt;
          &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
                 &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
                 &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
          &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Definitions for PrescriptionDAO.java and MyClient.java will remain the same.&lt;br /&gt;
The advantage of using Constructor Injection is that it can create the objects at the time of instantiation itself. Hence it guarantees the developer, that the objects will definitely get created and no exception will be raised. &lt;br /&gt;
&lt;br /&gt;
However, unlike [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Type_2-_Setter_Injection Setter injection] it won’t allow changes to the dependency, once it is created.&lt;br /&gt;
&lt;br /&gt;
=Advantages and Disadvantages=&lt;br /&gt;
&lt;br /&gt;
Advantage of using Dependency injection are &lt;br /&gt;
* Clean code which helps to separate out the logic and the instantiation modules. &lt;br /&gt;
* It is also easy to maintain the code with the use of configuration files where we can make changes in future whenever required. &lt;br /&gt;
* It is very easy to test the code using Dependency Injection.&lt;br /&gt;
* It makes the code more readable.&lt;br /&gt;
&lt;br /&gt;
Disadvantages are &lt;br /&gt;
* A developer cannot understand the code easily as there is an abstraction layer which is performing initializing and instantiation of objects. &lt;br /&gt;
* Developers need to have a certain level of expertise in coding such design patterns.&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
Hence, Dependency Injection design pattern is good enough to implement in the enterprise applications of large scale, as it helps in reusability, maintainability and testing.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
[1] [http://www.amazon.com/Spring-Action-Craig-Walls/dp/1932394354 Walls, C.,Briedenbach, R. ''Spring in Action'' Manning]&amp;lt;br&amp;gt;&lt;br /&gt;
[2] [http://www.amazon.com/Professional-Java-Development-Spring-Framework/dp/0764574833 Johnson, R., Hoeller, J., Arendsen, A. ''Professional Java Development with Spring Framework'' Wrox]&amp;lt;br&amp;gt;&lt;br /&gt;
[3] [http://www.springsource.org/ Spring Framework]&amp;lt;br&amp;gt;&lt;br /&gt;
[4] [http://www.opensymphony.com/xwork/ Xwork]&amp;lt;br&amp;gt;&lt;br /&gt;
[5] [http://static.springsource.org/spring/docs/2.5.x/reference/aop.html Aspect Oriented Programming]&amp;lt;br&amp;gt;&lt;br /&gt;
[6] [http://en.wikipedia.org/wiki/Circular_dependency Circular Dependency]&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=External Links=&lt;br /&gt;
[1] [http://www.codeproject.com/KB/architecture/DependencyInjection.aspx Dependency Injection for Loose Coupling]&amp;lt;br&amp;gt;&lt;br /&gt;
[2] [http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators Dependency injection]&amp;lt;br&amp;gt;&lt;br /&gt;
[3] [http://excalibur.apache.org/framework/index.html Excalibur Apache Avalon]&amp;lt;br&amp;gt;&lt;br /&gt;
[4] [http://www.picocontainer.org/ PicoContainer]&amp;lt;br&amp;gt;&lt;br /&gt;
[5] [http://hivelogic.com/ Hivelogic]&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
[1] [http://www.manning.com/seemann/ Seemann, M. ''Dependency Injection in .NET'' Manning]&amp;lt;br&amp;gt;&lt;br /&gt;
[2] [http://www.manning.com/prasanna/ Prassanna, D. ''Dependency Injection'' Manning]&amp;lt;br&amp;gt;&lt;br /&gt;
[3] [http://www.developer.com/net/csharp/article.php/3722931/Dependency-Injection-with-SpringNet.htm Dependency Injection with Spring .NET] &amp;lt;br&amp;gt;&lt;br /&gt;
[4] [http://needle.rubyforge.org/api/ Dependency Injection in Ruby]&lt;br /&gt;
[5] [http://onestepback.org/index.cgi/Tech/Ruby/DependencyInjectionInRuby.rdoc ]&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=40032</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=40032"/>
		<updated>2010-11-03T23:46:19Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability.[http://www.codeproject.com/KB/architecture/DependencyInjection.aspx] This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
== Definition ==&lt;br /&gt;
The basic concept of Dependency Injection(DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class.[http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators]&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control(IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
== Features of Dependency Injection ==&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
* More Testable- It makes it very easy to test the code, as objects get instantiated with values using configuration files.&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.[http://www.springsource.org/]&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is a highly effective command pattern framework that provides a lot of features for DI.[http://www.opensymphony.com/xwork/]&lt;br /&gt;
* '''Apache Avalon'''- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.[http://excalibur.apache.org/framework/index.html]&lt;br /&gt;
* '''PicoContainer''' - It is a highly focused DI framework available.[http://www.picocontainer.org/]&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.[http://hivelogic.com/]&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us consider a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object. We need some Assembler (DI Framework) to instantiate the Department field of Employee class. Rather than Employee class creating this object for itself, it will delegate this task of instantiation to any framework selected from above. To do this, it uses configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Types_of_Dependency_Injection section 3]. &lt;br /&gt;
&lt;br /&gt;
 '''''Employee.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( ){ }  &lt;br /&gt;
         &lt;br /&gt;
         setDepartment(dept){&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
         }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''Department.java'''''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName(){&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name){&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
The framework will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object. It will form an Employee object with a Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where the binding of beans is done as follows:&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
      &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
      &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	   &amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, one only needs to update the configuration file. There is no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is a technique to add the dependency for interfaces in components at run time. The components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using the Avalon framework.&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 '''''AccountApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
 {&lt;br /&gt;
        void getEntity(){&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
        }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''CustomerApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
 {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
        {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
        }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface. The ApplicationServiceImpl class implements the ApplicationService inteface, which in turn implements the ApplicationDAO interface, provided by the container.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
 {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationServiceImpl.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
  {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
         {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
          }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container, which uses configuration file for look up, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
            string implementClass =  &lt;br /&gt;
                                    System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
            ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
             &lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
The Configuration File that will be used by MyClass file to lookup the dependency configurations will be of type:&lt;br /&gt;
&lt;br /&gt;
 '''''App.Config'''''&lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
      &amp;lt;appSettings&amp;gt;&lt;br /&gt;
            &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
       &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
In this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference. The getEntity() that is invoked will actually depend on the dependency that is injected via the configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state(variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us consider an example of Setter injection by using Spring Framework.[3] Before using Spring, let us study some basic features of Spring. We will cover only a brief overview of the Spring Framework. &lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[http://static.springsource.org/spring/docs/2.5.x/reference/aop.html], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
Now let us see Setter injection using the Spring framework.&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is the class on which DoctorService depends. &amp;lt;br&amp;gt;[[image:di_image2.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
       { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
       }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
       { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
       }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
       {&lt;br /&gt;
              System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
              System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
       }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
        private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
                return  this.prescription;&lt;br /&gt;
        }&lt;br /&gt;
        public void setPrescription(String prescription) &lt;br /&gt;
        {&lt;br /&gt;
           this. prescription = prescription;&lt;br /&gt;
        }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
Here, the invoking object is responsible for setting the PrescriptionDAO dependency. There is no code inside the class that is creating new instance of PrescriptionDAO. This is because this task will be performed by the Spring container, by looking for dependencies of DoctorService inside applicationContext.xml file.&lt;br /&gt;
&lt;br /&gt;
The Spring framework uses a setter method to create this dependent object. Note the &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
       &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
                  &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
                  &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
       &amp;lt;/bean&amp;gt;&lt;br /&gt;
       &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
                 &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
                 &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
       &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions from inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
 public class MyClient&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(String args[])&lt;br /&gt;
        {&lt;br /&gt;
                Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
                BeanFactory factory =new XmlBeanFactory(res); &lt;br /&gt;
                //” doctorServiceId” is the same id defined in ApplicationContext.xml&lt;br /&gt;
                DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
         }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first the path for the ApplicationContext is specified, and then this file is used as a resource by the container. The BeanFactory container uses the xml file to access the bean defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However, Setter Injection unnecessarily adds to the abstraction. The developer needs to know which dependencies are needed when. On the other hand, it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;br /&gt;
&lt;br /&gt;
==Type 3- Constructor Injection==&lt;br /&gt;
&lt;br /&gt;
Constructor Injection is the DI technique of passing an object's dependencies to its constructor. It addresses the most common scenario where a class requires one or more Dependencies, and no reasonable local defaults are available.&lt;br /&gt;
&lt;br /&gt;
Constructor Injection addresses this scenario very well, because it guarantees that the Dependency is always present. If the depending class absolutely cannot function without the Dependency, such a guarantee is valuable. Constructor-injection enforces the order of initialization and prevents circular dependencies [http://en.wikipedia.org/wiki/Circular_dependency]. &lt;br /&gt;
On the other hand, with Setter injection, it is not clear, in which order things need to be instantiated. Apart from the guaranteed injection, this pattern is also very easy to implement. &lt;br /&gt;
&lt;br /&gt;
Continuing with the example mentioned above, we can implement the same using constructor injection as follows, &amp;lt;br&amp;gt; [[image:di_image3.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
         private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
         // constructor for instantiatng prescriptionDAO&lt;br /&gt;
         public DoctorService (prescriptionDAO)&lt;br /&gt;
         { &lt;br /&gt;
            this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
         }&lt;br /&gt;
         //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
          public void print()&lt;br /&gt;
          {	&lt;br /&gt;
               System.out.println(&amp;quot;prescription:&amp;quot; +prescriptionDAO.prescription);&lt;br /&gt;
               System.out.println(&amp;quot;dose: &amp;quot;+prescriptionDAO.dose); &lt;br /&gt;
          }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
In the example, you must have noticed the parametrized constructor which Spring framework uses to instantiate the value of prescriptionDAO. &lt;br /&gt;
Now, the question is- how Spring container will come to know whether it has to use Constructor injection or Setter Injection? Tags inside the &amp;lt;bean&amp;gt; tag will specify this:&lt;br /&gt;
* &amp;lt;property&amp;gt; tag   is used for Setter Injection&lt;br /&gt;
* &amp;lt;constructor-arg&amp;gt; is used for Constructor Injection.&lt;br /&gt;
&lt;br /&gt;
ApplicationContect.xml for Constructor injection will be:&lt;br /&gt;
 '''''ApplicationContect.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
                 &amp;lt;!-- constructor injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
 		 &amp;lt;constructor-arg&amp;gt;&lt;br /&gt;
                 &amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&lt;br /&gt;
                 &amp;lt;/constructor-arg&amp;gt;&lt;br /&gt;
          &amp;lt;/bean&amp;gt;&lt;br /&gt;
          &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
                 &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
                 &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
          &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Definitions for PrescriptionDAO.java and MyClient.java will remain the same.&lt;br /&gt;
The advantage of using Constructor Injection is that it can create the objects at the time of instantiation itself. Hence it guarantees the developer, that the objects will definitely get created and no exception will be raised. &lt;br /&gt;
&lt;br /&gt;
However, unlike [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Type_2-_Setter_Injection Setter injection] it won’t allow changes to the dependency, once it is created.&lt;br /&gt;
&lt;br /&gt;
=Advantages and Disadvantages=&lt;br /&gt;
&lt;br /&gt;
Advantage of using Dependency injection are &lt;br /&gt;
* Clean code which helps to separate out the logic and the instantiation modules. &lt;br /&gt;
* It is also easy to maintain the code with the use of configuration files where we can make changes in future whenever required. &lt;br /&gt;
* It is very easy to test the code using Dependency Injection.&lt;br /&gt;
* It makes the code more readable.&lt;br /&gt;
&lt;br /&gt;
But the down side of Dependency Injection are that, &lt;br /&gt;
* It is not quite easy to understand the code for developers as there seems to be an abstraction layer which is performing initializing and instantiation of objects. &lt;br /&gt;
* Moreover, developers should have an expertise in coding such design patterns.&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
Hence, Dependency Injection design pattern is good enough to implement in the enterprise applications of large scale, as it helps in reusability, maintainability and testing.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
[1] [http://www.amazon.com/Spring-Action-Craig-Walls/dp/1932394354 Walls, C.,Briedenbach, R. ''Spring in Action'' Manning]&amp;lt;br&amp;gt;&lt;br /&gt;
[2] [http://www.amazon.com/Professional-Java-Development-Spring-Framework/dp/0764574833 Johnson, R., Hoeller, J., Arendsen, A. ''Professional Java Development with Spring Framework'' Wrox]&amp;lt;br&amp;gt;&lt;br /&gt;
[3] [http://www.springsource.org/ Spring Framework]&amp;lt;br&amp;gt;&lt;br /&gt;
[4] [http://www.opensymphony.com/xwork/ Xwork]&amp;lt;br&amp;gt;&lt;br /&gt;
[5] [http://static.springsource.org/spring/docs/2.5.x/reference/aop.html Aspect Oriented Programming]&amp;lt;br&amp;gt;&lt;br /&gt;
[6] [http://en.wikipedia.org/wiki/Circular_dependency Circular Dependency]&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=External Links=&lt;br /&gt;
[1] [http://www.codeproject.com/KB/architecture/DependencyInjection.aspx Dependency Injection for Loose Coupling]&amp;lt;br&amp;gt;&lt;br /&gt;
[2] [http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators Dependency injection]&amp;lt;br&amp;gt;&lt;br /&gt;
[3] [http://excalibur.apache.org/framework/index.html Excalibur Apache Avalon]&amp;lt;br&amp;gt;&lt;br /&gt;
[4] [http://www.picocontainer.org/ PicoContainer]&amp;lt;br&amp;gt;&lt;br /&gt;
[5] [http://hivelogic.com/ Hivelogic]&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
[1] [http://www.manning.com/seemann/ Seemann, M. ''Dependency Injection in .NET'' Manning]&amp;lt;br&amp;gt;&lt;br /&gt;
[2] [http://www.manning.com/prasanna/ Prassanna, D. ''Dependency Injection'' Manning]&amp;lt;br&amp;gt;&lt;br /&gt;
[3] [http://www.developer.com/net/csharp/article.php/3722931/Dependency-Injection-with-SpringNet.htm Dependency Injection with Spring .NET] &amp;lt;br&amp;gt;&lt;br /&gt;
[4] [http://needle.rubyforge.org/api/ Dependency Injection in Ruby]&lt;br /&gt;
[5] [http://onestepback.org/index.cgi/Tech/Ruby/DependencyInjectionInRuby.rdoc ]&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=40028</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=40028"/>
		<updated>2010-11-03T23:30:21Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability.[http://www.codeproject.com/KB/architecture/DependencyInjection.aspx] This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
== Definition ==&lt;br /&gt;
The basic concept of Dependency Injection(DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class.[http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators]&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control(IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
== Features of Dependency Injection ==&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
* More Testable- It makes it very easy to test the code, as objects get instantiated with values using configuration files.&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.[http://www.springsource.org/]&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is a highly effective command pattern framework that provides a lot of features for DI.[http://www.opensymphony.com/xwork/]&lt;br /&gt;
* '''Apache Avalon'''- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.[http://excalibur.apache.org/framework/index.html]&lt;br /&gt;
* '''PicoContainer''' - It is a highly focused DI framework available.[http://www.picocontainer.org/]&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.[http://hivelogic.com/]&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us consider a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object. We need some Assembler (DI Framework) to instantiate the Department field of Employee class. Rather than Employee class creating this object for itself, it will delegate this task of instantiation to any framework selected from above. To do this, it uses configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Types_of_Dependency_Injection section 4]. &lt;br /&gt;
&lt;br /&gt;
 '''''Employee.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( ){ }  &lt;br /&gt;
         &lt;br /&gt;
         setDepartment(dept){&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
         }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''Department.java'''''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName(){&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name){&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
The framework will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object. It will form an Employee object with a Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where the binding of beans is done as follows:&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
      &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
      &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	   &amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, one only needs to update the configuration file. There is no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is a technique to add the dependency for interfaces in components at run time. The components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using the Avalon framework.&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 '''''AccountApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
 {&lt;br /&gt;
        void getEntity(){&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
        }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''CustomerApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
 {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
        {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
        }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface. The ApplicationServiceImpl class implements the ApplicationService inteface, which in turn implements the ApplicationDAO interface, provided by the container.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
 {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationServiceImpl.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
  {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
         {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
          }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container, which uses configuration file for look up, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
            string implementClass =  &lt;br /&gt;
                                    System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
            ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
             &lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
The Configuration File that will be used by MyClass file to lookup the dependency configurations will be of type:&lt;br /&gt;
&lt;br /&gt;
 '''''App.Config'''''&lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
      &amp;lt;appSettings&amp;gt;&lt;br /&gt;
            &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
       &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
In this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference. The getEntity() that is invoked will actually depend on the dependency that is injected via the configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state(variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us consider an example of Setter injection by using Spring Framework.[3] Before using Spring, let us study some basic features of Spring. We will cover only a brief overview of the Spring Framework. &lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[http://static.springsource.org/spring/docs/2.5.x/reference/aop.html], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
Now let us see Setter injection using the Spring framework.&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is the class on which DoctorService depends. &amp;lt;br&amp;gt;[[image:di_image2.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
       { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
       }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
       { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
       }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
       {&lt;br /&gt;
              System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
              System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
       }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
        private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
                return  this.prescription;&lt;br /&gt;
        }&lt;br /&gt;
        public void setPrescription(String prescription) &lt;br /&gt;
        {&lt;br /&gt;
           this. prescription = prescription;&lt;br /&gt;
        }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
Here, the invoking object is responsible for setting the PrescriptionDAO dependency. There is no code inside the class that is creating new instance of PrescriptionDAO. This is because this task will be performed by the Spring container, by looking for dependencies of DoctorService inside applicationContext.xml file.&lt;br /&gt;
&lt;br /&gt;
The Spring framework uses a setter method to create this dependent object. Note the &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
        &lt;br /&gt;
       &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
                  &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
                  &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
       &amp;lt;/bean&amp;gt;&lt;br /&gt;
       &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
                 &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
                 &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
       &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions from inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
 public class MyClient&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(String args[])&lt;br /&gt;
        {&lt;br /&gt;
                Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
                BeanFactory factory =new XmlBeanFactory(res); &lt;br /&gt;
                //” doctorServiceId” is the same id defined in ApplicationContext.xml&lt;br /&gt;
                DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
         }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first the path for the ApplicationContext is specified, and then this file is used as a resource by the container. The BeanFactory container uses the xml file to access the bean defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However, Setter Injection unnecessarily adds to the abstraction. The developer needs to know which dependencies are needed when. On the other hand, it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;br /&gt;
&lt;br /&gt;
==Type 3- Constructor Injection==&lt;br /&gt;
&lt;br /&gt;
Constructor Injection is the DI technique of passing an object's dependencies to its constructor. It addresses the most common scenario where a class requires one or more Dependencies, and no reasonable local defaults are available.&lt;br /&gt;
&lt;br /&gt;
Constructor Injection addresses this scenario very well, because it guarantees that the Dependency is always present. If the depending class absolutely cannot function without the Dependency, such a guarantee is valuable. Constructor-injection enforces the order of initialization and prevents circular dependencies [http://en.wikipedia.org/wiki/Circular_dependency]. &lt;br /&gt;
On the other hand, with Setter injection, it is not clear, in which order things need to be instantiated. Apart from the guaranteed injection, this pattern is also very easy to implement. &lt;br /&gt;
&lt;br /&gt;
Continuing with the example mentioned above, we can implement the same using constructor injection as follows, &amp;lt;br&amp;gt; [[image:di_image3.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
         private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
         // constructor for instantiatng prescriptionDAO&lt;br /&gt;
         public DoctorService (prescriptionDAO)&lt;br /&gt;
         { &lt;br /&gt;
            this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
         }&lt;br /&gt;
         //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
          public void print()&lt;br /&gt;
          {	&lt;br /&gt;
               System.out.println(&amp;quot;prescription:&amp;quot; +prescriptionDAO.prescription);&lt;br /&gt;
               System.out.println(&amp;quot;dose: &amp;quot;+prescriptionDAO.dose); &lt;br /&gt;
          }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
In the example, you must have noticed the parametrized constructor which Spring framework uses to instantiate the value of prescriptionDAO. &lt;br /&gt;
Now, the question is- how Spring container will come to know whether it has to use Constructor injection or Setter Injection? Tags inside the &amp;lt;bean&amp;gt; tag will specify this:&lt;br /&gt;
* &amp;lt;property&amp;gt; tag   is used for Setter Injection&lt;br /&gt;
* &amp;lt;constructor-arg&amp;gt; is used for Constructor Injection.&lt;br /&gt;
&lt;br /&gt;
ApplicationContect.xml for Constructor injection will be:&lt;br /&gt;
 '''''ApplicationContect.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
                 &amp;lt;!-- constructor injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
 		 &amp;lt;constructor-arg&amp;gt;&lt;br /&gt;
                 &amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&lt;br /&gt;
                 &amp;lt;/constructor-arg&amp;gt;&lt;br /&gt;
          &amp;lt;/bean&amp;gt;&lt;br /&gt;
          &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
                 &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
                 &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
          &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Definitions for PrescriptionDAO.java and MyClient.java will remain the same.&lt;br /&gt;
The advantage of using Constructor Injection is that it can create the objects at the time of instantiation itself. Hence it guarantees the developer, that the objects will definitely get created and no exception will be raised. &lt;br /&gt;
&lt;br /&gt;
However, unlike [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Type_2-_Setter_Injection Setter injection] it won’t allow changes to the dependency, once it is created.&lt;br /&gt;
&lt;br /&gt;
=Advantages and Disadvantages=&lt;br /&gt;
&lt;br /&gt;
Advantage of using Dependency injection are &lt;br /&gt;
* Clean code which helps to separate out the logic and the instantiation modules. &lt;br /&gt;
* It is also easy to maintain the code with the use of configuration files where we can make changes in future whenever required. &lt;br /&gt;
* It is very easy to test the code using Dependency Injection.&lt;br /&gt;
* It makes the code more readable.&lt;br /&gt;
&lt;br /&gt;
But the down side of Dependency Injection are that, &lt;br /&gt;
* It is not quite easy to understand the code for developers as there seems to be an abstraction layer which is performing initializing and instantiation of objects. &lt;br /&gt;
* Moreover, developers should have an expertise in coding such design patterns.&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
Hence, Dependency Injection design pattern is good enough to implement in the enterprise applications of large scale, as it helps in reusability, maintainability and testing.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
[1] [Spring in Action by Craig Walls, Ryan Briedenbach]&amp;lt;br&amp;gt;&lt;br /&gt;
[2] [Java Development with Spring Framework,  by Rod Johnson, Juergen Hoeller, Alef Arendsen, Thomas Risberg, Colin Sampaleanu]&amp;lt;br&amp;gt;&lt;br /&gt;
[3] [http://www.springsource.org/ Spring Framework]&amp;lt;br&amp;gt;&lt;br /&gt;
[4] [http://www.opensymphony.com/xwork/ Xwork]&amp;lt;br&amp;gt;&lt;br /&gt;
[5] [http://static.springsource.org/spring/docs/2.5.x/reference/aop.html Aspect Oriented Programming]&amp;lt;br&amp;gt;&lt;br /&gt;
[6] [http://en.wikipedia.org/wiki/Circular_dependency Circular Dependency]&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
=External Links=&lt;br /&gt;
[1] [http://www.codeproject.com/KB/architecture/DependencyInjection.aspx Dependency Injection for Loose Coupling]&amp;lt;br&amp;gt;&lt;br /&gt;
[2] [http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators Dependency injection]&amp;lt;br&amp;gt;&lt;br /&gt;
[3] [http://excalibur.apache.org/framework/index.html Excalibur Apache Avalon]&amp;lt;br&amp;gt;&lt;br /&gt;
[4] [http://www.picocontainer.org/ PicoContainer]&amp;lt;br&amp;gt;&lt;br /&gt;
[5] [http://hivelogic.com/ Hivelogic]&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
[1] [Dependency Injection in .NET by Mark Seemann]&amp;lt;br&amp;gt;&lt;br /&gt;
[2] [Dependency Injection by Dhanji R Prassanna]&amp;lt;br&amp;gt;&lt;br /&gt;
[3] [http://www.developer.com/net/csharp/article.php/3722931/Dependency-Injection-with-SpringNet.htm Dependency Injection with Spring .NET] &amp;lt;br&amp;gt;&lt;br /&gt;
[4] [http://needle.rubyforge.org/api/ Dependency Injection in Ruby]&lt;br /&gt;
[5] [http://onestepback.org/index.cgi/Tech/Ruby/DependencyInjectionInRuby.rdoc ]&amp;lt;br&amp;gt;&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39922</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39922"/>
		<updated>2010-11-03T15:14:14Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability.[http://www.codeproject.com/KB/architecture/DependencyInjection.aspx] This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection(DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class.[http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators]&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control(IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
= Features of Dependency Injection =&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.[http://www.springsource.org/]&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is a highly effective command pattern framework that provides a lot of features for DI.[http://www.opensymphony.com/xwork/]&lt;br /&gt;
* '''Apache Avalon'''- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.[http://excalibur.apache.org/framework/index.html]&lt;br /&gt;
* '''PicoContainer''' - It is a highly focused DI framework available.[http://www.picocontainer.org/]&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.[http://hivelogic.com/]&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us consider a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object. We need some Assembler (DI Framework) to instantiate the Department field of Employee class. Rather than Employee class creating this object for itself, it will delegate this task of instantiation to any framework selected from above. To do this, it uses configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Types_of_Dependency_Injection section 4]. &lt;br /&gt;
&lt;br /&gt;
 '''''Employee.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''Department.java'''''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
The framework will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object. It will form an Employee object with a Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where the binding of beans is done as follows:&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, one only needs to update the configuration file. There is no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is a technique to add the dependency for interfaces in components at run time. The components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using the Avalon framework.&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 '''''AccountApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 '''''CustomerApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface. The ApplicationServiceImpl class implements the ApplicationService inteface, which in turn implements the ApplicationDAO interface, provided by the container.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationServiceImpl.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container, which uses configuration file for look up, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
The Configuration File that will be used by MyClass file to lookup the dependency configurations will be of type:&lt;br /&gt;
&lt;br /&gt;
 '''''App.Config'''''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
In this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference. The getEntity() that is invoked will actually depend on the dependency that is injected via the configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state(variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us consider an example of Setter injection by using Spring Framework.[3] Before using Spring, let us study some basic features of Spring. We will cover only a brief overview of the Spring Framework. &lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[http://static.springsource.org/spring/docs/2.5.x/reference/aop.html], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
Now let us see Setter injection using the Spring framework.&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is the class on which DoctorService depends. &amp;lt;br&amp;gt;[[image:di_image2.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
           { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
           }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
           { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
            }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
            {&lt;br /&gt;
              System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
              System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
             }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
        private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
                return  this.prescription;&lt;br /&gt;
        }&lt;br /&gt;
        public void setPrescription(String prescription) &lt;br /&gt;
        {&lt;br /&gt;
           this. prescription = prescription;&lt;br /&gt;
         }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here, the invoking object is responsible for setting the PrescriptionDAO dependency. There is no code inside the class that is creating new instance of PrescriptionDAO. This is because this task will be performed by the Spring container, by looking for dependencies of DoctorService inside applicationContext.xml file.&lt;br /&gt;
&lt;br /&gt;
The Spring framework uses a setter method to create this dependent object. Note the &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
       &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
    &amp;lt;/bean&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
   &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions from inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
 public class MyClient&lt;br /&gt;
 {&lt;br /&gt;
    public static void main(String args[])&lt;br /&gt;
        {&lt;br /&gt;
                Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
                BeanFactory factory =new XmlBeanFactory(res); &lt;br /&gt;
                //” doctorServiceId” is the same id defined in ApplicationContext.xml&lt;br /&gt;
                DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
         }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first the path for the ApplicationContext is specified, and then this file is used as a resource by the container. The BeanFactory container uses the xml file to access the bean defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However, Setter Injection unnecessarily adds to the abstraction. The developer needs to know which dependencies are needed when. On the other hand, it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;br /&gt;
&lt;br /&gt;
==Type 3- Constructor Injection==&lt;br /&gt;
&lt;br /&gt;
Constructor Injection is the DI technique of passing an object's dependencies to its constructor. It addresses the most common scenario where a class requires one or more Dependencies, and no reasonable local defaults are available.&lt;br /&gt;
&lt;br /&gt;
Constructor Injection addresses this scenario very well, because it guarantees that the Dependency is always present. If the depending class absolutely cannot function without the Dependency, such a guarantee is valuable. Constructor-injection enforces the order of initialization and prevents circular dependencies [http://en.wikipedia.org/wiki/Circular_dependency]. &lt;br /&gt;
On the other hand, with Setter injection, it is not clear, in which order things need to be instantiated. Apart from the guaranteed injection, this pattern is also very easy to implement. &lt;br /&gt;
&lt;br /&gt;
Continuing with the example mentioned above, we can implement the same using constructor injection as follows, &amp;lt;br&amp;gt; [[image:di_image3.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
      private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
    // constructor for instantiatng prescriptionDAO&lt;br /&gt;
      public DoctorService (prescriptionDAO)&lt;br /&gt;
         { &lt;br /&gt;
            this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
         }&lt;br /&gt;
 //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
 public void print()&lt;br /&gt;
         {	&lt;br /&gt;
               System.out.println(&amp;quot;prescription:&amp;quot; +prescriptionDAO.prescription);&lt;br /&gt;
               System.out.println(&amp;quot;dose: &amp;quot;+prescriptionDAO.dose); &lt;br /&gt;
         }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
In the example, you must have noticed the parametrized constructor which Spring framework uses to instantiate the value of prescriptionDAO. &lt;br /&gt;
Now, the question is- how Spring container will come to know whether it has to use Constructor injection or Setter Injection? Tags inside the &amp;lt;bean&amp;gt; tag will specify this:&lt;br /&gt;
* &amp;lt;property&amp;gt; tag   is used for Setter Injection&lt;br /&gt;
* &amp;lt;constructor-arg&amp;gt; is used for Constructor Injection.&lt;br /&gt;
&lt;br /&gt;
ApplicationContect.xml for Constructor injection will be:&lt;br /&gt;
 '''''ApplicationContect.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
                 &amp;lt;!-- constructor injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
 		 &amp;lt;constructor-arg&amp;gt;&lt;br /&gt;
                 &amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&lt;br /&gt;
                 &amp;lt;/constructor-arg&amp;gt;&lt;br /&gt;
   &amp;lt;/bean&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Definitions for PrescriptionDAO.java and MyClient.java will remain the same.&lt;br /&gt;
The advantage of using Constructor Injection is that it can create the objects at the time of instantiation itself. Hence it guarantees the developer, that the objects will definitely get created and no exception will be raised. However, unlike [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Type_2-_Setter_Injection Setter injection] it won’t allow changes to the dependency, once it is created.&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
[1] [http://www.codeproject.com/KB/architecture/DependencyInjection.aspx Dependency Injection for Loose Coupling]&amp;lt;br&amp;gt;&lt;br /&gt;
[2] [http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators Dependency injection]&amp;lt;br&amp;gt;&lt;br /&gt;
[3] [http://www.springsource.org/ Spring Framework]&amp;lt;br&amp;gt;&lt;br /&gt;
[4] [http://www.opensymphony.com/xwork/ Xwork]&amp;lt;br&amp;gt;&lt;br /&gt;
[5] [http://excalibur.apache.org/framework/index.html Excalibur Apache Avalon]&amp;lt;br&amp;gt;&lt;br /&gt;
[6] [http://www.picocontainer.org/ PicoContainer]&amp;lt;br&amp;gt;&lt;br /&gt;
[7] [http://hivelogic.com/ Hivelogic]&amp;lt;br&amp;gt;&lt;br /&gt;
[8] [http://static.springsource.org/spring/docs/2.5.x/reference/aop.html Aspect Oriented Programming]&amp;lt;br&amp;gt;&lt;br /&gt;
[9] [http://en.wikipedia.org/wiki/Circular_dependency Circular Dependency]&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39920</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39920"/>
		<updated>2010-11-03T15:09:02Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability.[http://www.codeproject.com/KB/architecture/DependencyInjection.aspx] This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection(DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class.[http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators]&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control(IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
= Features of Dependency Injection =&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.[http://www.springsource.org/]&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is a highly effective command pattern framework that provides a lot of features for DI.[http://www.opensymphony.com/xwork/]&lt;br /&gt;
* '''Apache Avalon'''- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.[http://excalibur.apache.org/framework/index.html]&lt;br /&gt;
* '''PicoContainer''' - It is a highly focused DI framework available.[http://www.picocontainer.org/]&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.[http://hivelogic.com/]&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us consider a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object. We need some Assembler (DI Framework) to instantiate the Department field of Employee class. Rather than Employee class creating this object for itself, it will delegate this task of instantiation to any framework selected from above. To do this, it uses configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Types_of_Dependency_Injection section 4]. &lt;br /&gt;
&lt;br /&gt;
 '''''Employee.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''Department.java'''''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
The framework will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object. It will form an Employee object with a Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where the binding of beans is done as follows:&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, one only needs to update the configuration file. There is no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is a technique to add the dependency for interfaces in components at run time. The components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using the Avalon framework.&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 '''''AccountApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 '''''CustomerApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface. The ApplicationServiceImpl class implements the ApplicationService inteface, which in turn implements the ApplicationDAO interface, provided by the container.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationServiceImpl.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container, which uses configuration file for look up, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
The Configuration File that will be used by MyClass file to lookup the dependency configurations will be of type:&lt;br /&gt;
&lt;br /&gt;
 '''''App.Config'''''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
In this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference. The getEntity() that is invoked will actually depend on the dependency that is injected via the configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state(variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us consider an example of Setter injection by using Spring Framework.[3] Before using Spring, let us study some basic features of Spring. We will cover only a brief overview of the Spring Framework. &lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[ ], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
Now let us see Setter injection using the Spring framework.&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is the class on which DoctorService depends. &amp;lt;br&amp;gt;[[image:di_image2.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
           { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
           }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
           { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
            }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
            {&lt;br /&gt;
              System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
              System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
             }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
        private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
                return  this.prescription;&lt;br /&gt;
        }&lt;br /&gt;
        public void setPrescription(String prescription) &lt;br /&gt;
        {&lt;br /&gt;
           this. prescription = prescription;&lt;br /&gt;
         }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here, the invoking object is responsible for setting the PrescriptionDAO dependency. There is no code inside the class that is creating new instance of PrescriptionDAO. This is because this task will be performed by the Spring container, by looking for dependencies of DoctorService inside applicationContext.xml file.&lt;br /&gt;
&lt;br /&gt;
The Spring framework uses a setter method to create this dependent object. Note the &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
       &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
    &amp;lt;/bean&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
   &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions from inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
 public class MyClient&lt;br /&gt;
 {&lt;br /&gt;
    public static void main(String args[])&lt;br /&gt;
        {&lt;br /&gt;
                Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
                BeanFactory factory =new XmlBeanFactory(res); &lt;br /&gt;
                //” doctorServiceId” is the same id defined in ApplicationContext.xml&lt;br /&gt;
                DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
         }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first the path for the ApplicationContext is specified, and then this file is used as a resource by the container. The BeanFactory container uses the xml file to access the bean defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However, Setter Injection unnecessarily adds to the abstraction. The developer needs to know which dependencies are needed when. On the other hand, it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;br /&gt;
&lt;br /&gt;
==Type 3- Constructor Injection==&lt;br /&gt;
&lt;br /&gt;
Constructor Injection is the DI technique of passing an object's dependencies to its constructor. It addresses the most common scenario where a class requires one or more Dependencies, and no reasonable local defaults are available.&lt;br /&gt;
&lt;br /&gt;
Constructor Injection addresses this scenario very well, because it guarantees that the Dependency is always present. If the depending class absolutely cannot function without the Dependency, such a guarantee is valuable. Constructor-injection enforces the order of initialization and prevents circular dependencies http://en.wikipedia.org/wiki/Circular_dependency. &lt;br /&gt;
On the other hand, with Setter injection, it is not clear, in which order things need to be instantiated. Apart from the guaranteed injection, this pattern is also very easy to implement. &lt;br /&gt;
&lt;br /&gt;
Continuing with the example mentioned above, we can implement the same using constructor injection as follows, &amp;lt;br&amp;gt; [[image:di_image3.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
      private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
    // constructor for instantiatng prescriptionDAO&lt;br /&gt;
      public DoctorService (prescriptionDAO)&lt;br /&gt;
         { &lt;br /&gt;
            this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
         }&lt;br /&gt;
 //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
 public void print()&lt;br /&gt;
         {	&lt;br /&gt;
               System.out.println(&amp;quot;prescription:&amp;quot; +prescriptionDAO.prescription);&lt;br /&gt;
               System.out.println(&amp;quot;dose: &amp;quot;+prescriptionDAO.dose); &lt;br /&gt;
         }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
In the example, you must have noticed the parametrized constructor which Spring framework uses to instantiate the value of prescriptionDAO. &lt;br /&gt;
Now, the question is- how Spring container will come to know whether it has to use Constructor injection or Setter Injection? Tags inside the &amp;lt;bean&amp;gt; tag will specify this:&lt;br /&gt;
* &amp;lt;property&amp;gt; tag   is used for Setter Injection&lt;br /&gt;
* &amp;lt;constructor-arg&amp;gt; is used for Constructor Injection.&lt;br /&gt;
&lt;br /&gt;
ApplicationContect.xml for Constructor injection will be:&lt;br /&gt;
 '''''ApplicationContect.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
                 &amp;lt;!-- constructor injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
 		 &amp;lt;constructor-arg&amp;gt;&lt;br /&gt;
                 &amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&lt;br /&gt;
                 &amp;lt;/constructor-arg&amp;gt;&lt;br /&gt;
   &amp;lt;/bean&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Definitions for PrescriptionDAO.java and MyClient.java will remain the same.&lt;br /&gt;
The advantage of using Constructor Injection is that it can create the objects at the time of instantiation itself. Hence it guarantees the developer, that the objects will definitely get created and no exception will be raised. However, unlike [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Type_2-_Setter_Injection Setter injection] it won’t allow changes to the dependency, once it is created.&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
[1] [http://www.codeproject.com/KB/architecture/DependencyInjection.aspx Dependency Injection for Loose Coupling]&amp;lt;br&amp;gt;&lt;br /&gt;
[2] [http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators Dependency injection]&amp;lt;br&amp;gt;&lt;br /&gt;
[3] [http://www.springsource.org/ Spring Framework]&amp;lt;br&amp;gt;&lt;br /&gt;
[4] [http://www.opensymphony.com/xwork/ Xwork]&amp;lt;br&amp;gt;&lt;br /&gt;
[5] [http://excalibur.apache.org/framework/index.html Excalibur Apache Avalon]&amp;lt;br&amp;gt;&lt;br /&gt;
[6] [http://www.picocontainer.org/ PicoContainer]&amp;lt;br&amp;gt;&lt;br /&gt;
[7] [http://hivelogic.com/ Hivelogic]&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39919</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39919"/>
		<updated>2010-11-03T15:07:01Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: /* References and Notes */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability.[http://www.codeproject.com/KB/architecture/DependencyInjection.aspx] This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection(DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class.[http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators]&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control(IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
= Features of Dependency Injection =&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.[http://www.springsource.org/]&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is a highly effective command pattern framework that provides a lot of features for DI.[http://www.opensymphony.com/xwork/]&lt;br /&gt;
* '''Apache Avalon'''- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.[http://excalibur.apache.org/framework/index.html]&lt;br /&gt;
* '''PicoContainer''' - It is a highly focused DI framework available.[http://www.picocontainer.org/]&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.[http://hivelogic.com/]&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us consider a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object. We need some Assembler (DI Framework) to instantiate the Department field of Employee class. Rather than Employee class creating this object for itself, it will delegate this task of instantiation to any framework selected from above. To do this, it uses configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Types_of_Dependency_Injection section 4]. &lt;br /&gt;
&lt;br /&gt;
 '''''Employee.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''Department.java'''''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
The framework will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object. It will form an Employee object with a Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where the binding of beans is done as follows:&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, one only needs to update the configuration file. There is no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is a technique to add the dependency for interfaces in components at run time. The components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using the Avalon framework.&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 '''''AccountApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 '''''CustomerApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface. The ApplicationServiceImpl class implements the ApplicationService inteface, which in turn implements the ApplicationDAO interface, provided by the container.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationServiceImpl.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container, which uses configuration file for look up, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
The Configuration File that will be used by MyClass file to lookup the dependency configurations will be of type:&lt;br /&gt;
&lt;br /&gt;
 '''''App.Config'''''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
In this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference. The getEntity() that is invoked will actually depend on the dependency that is injected via the configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state(variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us consider an example of Setter injection by using Spring Framework.[3] Before using Spring, let us study some basic features of Spring. We will cover only a brief overview of the Spring Framework. &lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[ ], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
Now let us see Setter injection using the Spring framework.&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is the class on which DoctorService depends. &amp;lt;br&amp;gt;[[image:di_image2.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
           { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
           }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
           { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
            }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
            {&lt;br /&gt;
              System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
              System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
             }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
        private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
                return  this.prescription;&lt;br /&gt;
        }&lt;br /&gt;
        public void setPrescription(String prescription) &lt;br /&gt;
        {&lt;br /&gt;
           this. prescription = prescription;&lt;br /&gt;
         }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here, the invoking object is responsible for setting the PrescriptionDAO dependency. There is no code inside the class that is creating new instance of PrescriptionDAO. This is because this task will be performed by the Spring container, by looking for dependencies of DoctorService inside applicationContext.xml file.&lt;br /&gt;
&lt;br /&gt;
The Spring framework uses a setter method to create this dependent object. Note the &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
       &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
    &amp;lt;/bean&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
   &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions from inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
 public class MyClient&lt;br /&gt;
 {&lt;br /&gt;
    public static void main(String args[])&lt;br /&gt;
        {&lt;br /&gt;
                Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
                BeanFactory factory =new XmlBeanFactory(res); &lt;br /&gt;
                //” doctorServiceId” is the same id defined in ApplicationContext.xml&lt;br /&gt;
                DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
         }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first the path for the ApplicationContext is specified, and then this file is used as a resource by the container. The BeanFactory container uses the xml file to access the bean defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However, Setter Injection unnecessarily adds to the abstraction. The developer needs to know which dependencies are needed when. On the other hand, it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;br /&gt;
&lt;br /&gt;
==Type 3- Constructor Injection==&lt;br /&gt;
&lt;br /&gt;
Constructor Injection is the DI technique of passing an object's dependencies to its constructor. It addresses the most common scenario where a class requires one or more Dependencies, and no reasonable local defaults are available.&lt;br /&gt;
&lt;br /&gt;
Constructor Injection addresses this scenario very well, because it guarantees that the Dependency is always present. If the depending class absolutely cannot function without the Dependency, such a guarantee is valuable. Constructor-injection enforces the order of initialization and prevents circular dependencies http://en.wikipedia.org/wiki/Circular_dependency. &lt;br /&gt;
On the other hand, with Setter injection, it is not clear, in which order things need to be instantiated. Apart from the guaranteed injection, this pattern is also very easy to implement. &lt;br /&gt;
&lt;br /&gt;
Continuing with the example mentioned above, we can implement the same using constructor injection as follows, &amp;lt;br&amp;gt; [[image:di_image3.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
      private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
    // constructor for instantiatng prescriptionDAO&lt;br /&gt;
      public DoctorService (prescriptionDAO)&lt;br /&gt;
         { &lt;br /&gt;
            this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
         }&lt;br /&gt;
 //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
 public void print()&lt;br /&gt;
         {	&lt;br /&gt;
               System.out.println(&amp;quot;prescription:&amp;quot; +prescriptionDAO.prescription);&lt;br /&gt;
               System.out.println(&amp;quot;dose: &amp;quot;+prescriptionDAO.dose); &lt;br /&gt;
         }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
In the example, you must have noticed the parametrized constructor which Spring framework uses to instantiate the value of prescriptionDAO. &lt;br /&gt;
Now, the question is- how Spring container will come to know whether it has to use Constructor injection or Setter Injection? Tags inside the &amp;lt;bean&amp;gt; tag will specify this:&lt;br /&gt;
* &amp;lt;property&amp;gt; tag   is used for Setter Injection&lt;br /&gt;
* &amp;lt;constructor-arg&amp;gt; is used for Constructor Injection.&lt;br /&gt;
&lt;br /&gt;
ApplicationContect.xml for Constructor injection will be:&lt;br /&gt;
 '''''ApplicationContect.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
                 &amp;lt;!-- constructor injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
 		 &amp;lt;constructor-arg&amp;gt;&lt;br /&gt;
                 &amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&lt;br /&gt;
                 &amp;lt;/constructor-arg&amp;gt;&lt;br /&gt;
   &amp;lt;/bean&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Definitions for PrescriptionDAO.java and MyClient.java will remain the same.&lt;br /&gt;
The advantage of using Constructor Injection is that it can create the objects at the time of instantiation itself. Hence it guarantees the developer, that the objects will definitely get created and no exception will be raised. However, unlike [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Type_2-_Setter_Injection Setter injection] it won’t allow changes to the dependency, once it is created.&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
= References and Notes =&lt;br /&gt;
[1] [http://www.codeproject.com/KB/architecture/DependencyInjection.aspx Dependency Injection for Loose Coupling]&amp;lt;br&amp;gt;&lt;br /&gt;
[2] [http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators Dependency injection]&amp;lt;br&amp;gt;&lt;br /&gt;
[3] [http://www.springsource.org/ Spring Framework]&amp;lt;br&amp;gt;&lt;br /&gt;
[4] [http://www.opensymphony.com/xwork/ Xwork]&amp;lt;br&amp;gt;&lt;br /&gt;
[5] [http://excalibur.apache.org/framework/index.html Excalibur Apache Avalon]&amp;lt;br&amp;gt;&lt;br /&gt;
[6] [http://www.picocontainer.org/ PicoContainer]&amp;lt;br&amp;gt;&lt;br /&gt;
[7] [http://hivelogic.com/ Hivelogic]&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39918</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39918"/>
		<updated>2010-11-03T15:06:15Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability.[http://www.codeproject.com/KB/architecture/DependencyInjection.aspx] This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection(DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class.[http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators]&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control(IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
= Features of Dependency Injection =&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.[http://www.springsource.org/]&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is a highly effective command pattern framework that provides a lot of features for DI.[http://www.opensymphony.com/xwork/]&lt;br /&gt;
* '''Apache Avalon'''- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.[http://excalibur.apache.org/framework/index.html]&lt;br /&gt;
* '''PicoContainer''' - It is a highly focused DI framework available.[http://www.picocontainer.org/]&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.[http://hivelogic.com/]&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us consider a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object. We need some Assembler (DI Framework) to instantiate the Department field of Employee class. Rather than Employee class creating this object for itself, it will delegate this task of instantiation to any framework selected from above. To do this, it uses configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Types_of_Dependency_Injection section 4]. &lt;br /&gt;
&lt;br /&gt;
 '''''Employee.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''Department.java'''''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
The framework will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object. It will form an Employee object with a Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where the binding of beans is done as follows:&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, one only needs to update the configuration file. There is no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is a technique to add the dependency for interfaces in components at run time. The components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using the Avalon framework.&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 '''''AccountApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 '''''CustomerApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface. The ApplicationServiceImpl class implements the ApplicationService inteface, which in turn implements the ApplicationDAO interface, provided by the container.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationServiceImpl.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container, which uses configuration file for look up, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
The Configuration File that will be used by MyClass file to lookup the dependency configurations will be of type:&lt;br /&gt;
&lt;br /&gt;
 '''''App.Config'''''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
In this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference. The getEntity() that is invoked will actually depend on the dependency that is injected via the configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state(variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us consider an example of Setter injection by using Spring Framework.[3] Before using Spring, let us study some basic features of Spring. We will cover only a brief overview of the Spring Framework. &lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[ ], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
Now let us see Setter injection using the Spring framework.&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is the class on which DoctorService depends. &amp;lt;br&amp;gt;[[image:di_image2.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
           { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
           }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
           { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
            }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
            {&lt;br /&gt;
              System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
              System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
             }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
        private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
                return  this.prescription;&lt;br /&gt;
        }&lt;br /&gt;
        public void setPrescription(String prescription) &lt;br /&gt;
        {&lt;br /&gt;
           this. prescription = prescription;&lt;br /&gt;
         }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here, the invoking object is responsible for setting the PrescriptionDAO dependency. There is no code inside the class that is creating new instance of PrescriptionDAO. This is because this task will be performed by the Spring container, by looking for dependencies of DoctorService inside applicationContext.xml file.&lt;br /&gt;
&lt;br /&gt;
The Spring framework uses a setter method to create this dependent object. Note the &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
       &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
    &amp;lt;/bean&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
   &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions from inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
 public class MyClient&lt;br /&gt;
 {&lt;br /&gt;
    public static void main(String args[])&lt;br /&gt;
        {&lt;br /&gt;
                Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
                BeanFactory factory =new XmlBeanFactory(res); &lt;br /&gt;
                //” doctorServiceId” is the same id defined in ApplicationContext.xml&lt;br /&gt;
                DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
         }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first the path for the ApplicationContext is specified, and then this file is used as a resource by the container. The BeanFactory container uses the xml file to access the bean defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However, Setter Injection unnecessarily adds to the abstraction. The developer needs to know which dependencies are needed when. On the other hand, it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;br /&gt;
&lt;br /&gt;
==Type 3- Constructor Injection==&lt;br /&gt;
&lt;br /&gt;
Constructor Injection is the DI technique of passing an object's dependencies to its constructor. It addresses the most common scenario where a class requires one or more Dependencies, and no reasonable local defaults are available.&lt;br /&gt;
&lt;br /&gt;
Constructor Injection addresses this scenario very well, because it guarantees that the Dependency is always present. If the depending class absolutely cannot function without the Dependency, such a guarantee is valuable. Constructor-injection enforces the order of initialization and prevents circular dependencies http://en.wikipedia.org/wiki/Circular_dependency. &lt;br /&gt;
On the other hand, with Setter injection, it is not clear, in which order things need to be instantiated. Apart from the guaranteed injection, this pattern is also very easy to implement. &lt;br /&gt;
&lt;br /&gt;
Continuing with the example mentioned above, we can implement the same using constructor injection as follows, &amp;lt;br&amp;gt; [[image:di_image3.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
      private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
    // constructor for instantiatng prescriptionDAO&lt;br /&gt;
      public DoctorService (prescriptionDAO)&lt;br /&gt;
         { &lt;br /&gt;
            this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
         }&lt;br /&gt;
 //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
 public void print()&lt;br /&gt;
         {	&lt;br /&gt;
               System.out.println(&amp;quot;prescription:&amp;quot; +prescriptionDAO.prescription);&lt;br /&gt;
               System.out.println(&amp;quot;dose: &amp;quot;+prescriptionDAO.dose); &lt;br /&gt;
         }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
In the example, you must have noticed the parametrized constructor which Spring framework uses to instantiate the value of prescriptionDAO. &lt;br /&gt;
Now, the question is- how Spring container will come to know whether it has to use Constructor injection or Setter Injection? Tags inside the &amp;lt;bean&amp;gt; tag will specify this:&lt;br /&gt;
* &amp;lt;property&amp;gt; tag   is used for Setter Injection&lt;br /&gt;
* &amp;lt;constructor-arg&amp;gt; is used for Constructor Injection.&lt;br /&gt;
&lt;br /&gt;
ApplicationContect.xml for Constructor injection will be:&lt;br /&gt;
 '''''ApplicationContect.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
                 &amp;lt;!-- constructor injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
 		 &amp;lt;constructor-arg&amp;gt;&lt;br /&gt;
                 &amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&lt;br /&gt;
                 &amp;lt;/constructor-arg&amp;gt;&lt;br /&gt;
   &amp;lt;/bean&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Definitions for PrescriptionDAO.java and MyClient.java will remain the same.&lt;br /&gt;
The advantage of using Constructor Injection is that it can create the objects at the time of instantiation itself. Hence it guarantees the developer, that the objects will definitely get created and no exception will be raised. However, unlike [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Type_2-_Setter_Injection Setter injection] it won’t allow changes to the dependency, once it is created.&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
= References and Notes =&lt;br /&gt;
[1] [http://www.codeproject.com/KB/architecture/DependencyInjection.aspx Dependency Injection for Loose Coupling]&lt;br /&gt;
[2] [http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators Dependency injection]&lt;br /&gt;
[3] [http://www.springsource.org/ Spring Framework]&lt;br /&gt;
[4] [http://www.opensymphony.com/xwork/ Xwork]&lt;br /&gt;
[5] [http://excalibur.apache.org/framework/index.html Excalibur Apache Avalon]&lt;br /&gt;
[6] [http://www.picocontainer.org/ PicoContainer]&lt;br /&gt;
[7] [http://hivelogic.com/ Hivelogic]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39917</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39917"/>
		<updated>2010-11-03T14:45:04Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability.[http://www.codeproject.com/KB/architecture/DependencyInjection.aspx] This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection(DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class.[http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators]&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control(IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
= Features of Dependency Injection =&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.[http://www.springsource.org/]&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is a highly effective command pattern framework that provides a lot of features for DI.[http://www.opensymphony.com/xwork/]&lt;br /&gt;
* '''Apache Avalon'''- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.[http://excalibur.apache.org/framework/index.html]&lt;br /&gt;
* '''PicoContainer''' - It is a highly focused DI framework available.[http://www.picocontainer.org/]&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.[http://hivelogic.com/]&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us consider a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object. We need some Assembler (DI Framework) to instantiate the Department field of Employee class. Rather than Employee class creating this object for itself, it will delegate this task of instantiation to any framework selected from above. To do this, it uses configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Types_of_Dependency_Injection section 4]. &lt;br /&gt;
&lt;br /&gt;
 '''''Employee.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''Department.java'''''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
The framework will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object. It will form an Employee object with a Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where the binding of beans is done as follows:&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, one only needs to update the configuration file. There is no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is a technique to add the dependency for interfaces in components at run time. The components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using the Avalon framework:////////////&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 '''''AccountApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 '''''CustomerApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface. The ApplicationServiceImpl class implements the ApplicationService inteface, which in turn implements the ApplicationDAO interface, provided by the container.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationServiceImpl.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container, which uses configuration file for look up, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
The Configuration File that will be used by MyClass file to lookup the dependency configurations will be of type:&lt;br /&gt;
&lt;br /&gt;
 '''''App.Config'''''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
In this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference. The getEntity() that is invoked will actually depend on the dependency that is injected via the configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state (variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us consider an example of Setter injection by using Spring Framework. [/////////////////////] Before using Spring, let us study some basic features of Spring. We will cover only a brief overview of the Spring Framework. For better understanding of Spring, please visit the site:  [ ////////////////////////////]&lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[ ], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
Now let us see Setter injection using the Spring framework.&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is the class on which DoctorService depends. &amp;lt;br&amp;gt;[[image:di_image2.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
           { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
           }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
           { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
            }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
            {&lt;br /&gt;
              System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
              System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
             }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
        private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
                return  this.prescription;&lt;br /&gt;
        }&lt;br /&gt;
        public void setPrescription(String prescription) &lt;br /&gt;
        {&lt;br /&gt;
           this. prescription = prescription;&lt;br /&gt;
         }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here, the invoking object is responsible for setting the PrescriptionDAO dependency. There is no code inside the class that is creating new instance of PrescriptionDAO. This is because this task will be performed by the Spring container, by looking for dependencies of DoctorService inside applicationContext.xml file.&lt;br /&gt;
&lt;br /&gt;
The Spring framework uses a setter method to create this dependent object. Note the &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
       &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
    &amp;lt;/bean&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
   &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions from inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
 public class MyClient&lt;br /&gt;
 {&lt;br /&gt;
    public static void main(String args[])&lt;br /&gt;
        {&lt;br /&gt;
                Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
                BeanFactory factory =new XmlBeanFactory(res); &lt;br /&gt;
                //” doctorServiceId” is the same id defined in ApplicationContext.xml&lt;br /&gt;
                DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
         }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first the path for the ApplicationContext is specified, and then this file is used as a resource by the container. The BeanFactory container uses the xml file to access the bean defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However, Setter Injection unnecessarily adds to the abstraction. The developer needs to know which dependencies are needed when. On the other hand, it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;br /&gt;
&lt;br /&gt;
==Type 3- Constructor Injection==&lt;br /&gt;
&lt;br /&gt;
Constructor Injection is the DI technique of passing an object's dependencies to its constructor. It addresses the most common scenario where a class requires one or more Dependencies, and no reasonable local defaults are available.&lt;br /&gt;
&lt;br /&gt;
Constructor Injection addresses this scenario very well, because it guarantees that the Dependency is always present. If the depending class absolutely cannot function without the Dependency, such a guarantee is valuable. Constructor-injection enforces the order of initialization and prevents circular dependencies http://en.wikipedia.org/wiki/Circular_dependency. &lt;br /&gt;
On the other hand, with Setter injection, it is not clear, in which order things need to be instantiated. Apart from the guaranteed injection, this pattern is also very easy to implement. &lt;br /&gt;
&lt;br /&gt;
Continuing with the example mentioned above, we can implement the same using constructor injection as follows, &amp;lt;br&amp;gt; [[image:di_image3.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
      private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
    // constructor for instantiatng prescriptionDAO&lt;br /&gt;
      public DoctorService (prescriptionDAO)&lt;br /&gt;
         { &lt;br /&gt;
            this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
         }&lt;br /&gt;
 //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
 public void print()&lt;br /&gt;
         {	&lt;br /&gt;
               System.out.println(&amp;quot;prescription:&amp;quot; +prescriptionDAO.prescription);&lt;br /&gt;
               System.out.println(&amp;quot;dose: &amp;quot;+prescriptionDAO.dose); &lt;br /&gt;
         }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
In the example, you must have noticed the parametrized constructor which Spring framework uses to instantiate the value of prescriptionDAO. &lt;br /&gt;
Now, the question is- how Spring container will come to know whether it has to use Constructor injection or Setter Injection? Tags inside the &amp;lt;bean&amp;gt; tag will specify this:&lt;br /&gt;
* &amp;lt;property&amp;gt; tag   is used for Setter Injection&lt;br /&gt;
* &amp;lt;constructor-arg&amp;gt; is used for Constructor Injection.&lt;br /&gt;
&lt;br /&gt;
ApplicationContect.xml for Constructor injection will be:&lt;br /&gt;
 '''''ApplicationContect.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
                 &amp;lt;!-- constructor injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
 		 &amp;lt;constructor-arg&amp;gt;&lt;br /&gt;
                 &amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&lt;br /&gt;
                 &amp;lt;/constructor-arg&amp;gt;&lt;br /&gt;
   &amp;lt;/bean&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Definitions for PrescriptionDAO.java and MyClient.java will remain the same.&lt;br /&gt;
The advantage of using Constructor Injection is that it can create the objects at the time of instantiation itself. Hence it guarantees the developer, that the objects will definitely get created and no exception will be raised. However, unlike [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Type_2-_Setter_Injection Setter injection] it won’t allow changes to the dependency, once it is created.&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
= References and Notes =&lt;br /&gt;
= Further Reading =&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39902</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39902"/>
		<updated>2010-11-03T05:21:08Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: /* Type 3- Constructor Injection */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is a highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* '''Apache Avalon'''- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is a highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us consider a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object. We need some Assembler (DI Framework) to instantiate the Department field of Employee class. Rather than Employee class creating this object for itself, it will delegate this task of instantiation to any framework selected from above. To do this, it uses configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Types_of_Dependency_Injection section 4]. &lt;br /&gt;
&lt;br /&gt;
 '''''Employee.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''Department.java'''''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
The framework will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object. It will form an Employee object with a Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where the binding of beans is done as follows:&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, one only needs to update the configuration file. There is no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is a technique to add the dependency for interfaces in components at run time. The components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using the Avalon framework: ////////////////////////////////////////provide external link&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 '''''AccountApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 '''''CustomerApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface. The ApplicationServiceImpl class implements the ApplicationService inteface, which in turn implements the ApplicationDAO interface, provided by the container.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationServiceImpl.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container, which uses configuration file for look up, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
The Configuration File that will be used by MyClass file to lookup the dependency configurations will be of type:&lt;br /&gt;
&lt;br /&gt;
 '''''App.Config'''''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
In this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference. The getEntity() that is invoked will actually depend on the dependency that is injected via the configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state (variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us consider an example of Setter injection by using Spring Framework. [/////////////////////] Before using Spring, let us study some basic features of Spring. We will cover only a brief overview of the Spring Framework. For better understanding of Spring, please visit the site:  [ ////////////////////////////]&lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[ ], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
Now let us see Setter injection using the Spring framework.&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is the class on which DoctorService depends. &amp;lt;br&amp;gt;[[image:di_image2.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
           { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
           }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
           { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
            }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
            {&lt;br /&gt;
              System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
              System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
             }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
        private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
                return  this.prescription;&lt;br /&gt;
        }&lt;br /&gt;
        public void setPrescription(String prescription) &lt;br /&gt;
        {&lt;br /&gt;
           this. prescription = prescription;&lt;br /&gt;
         }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here, the invoking object is responsible for setting the PrescriptionDAO dependency. There is no code inside the class that is creating new instance of PrescriptionDAO. This is because this task will be performed by the Spring container, by looking for dependencies of DoctorService inside applicationContext.xml file.&lt;br /&gt;
&lt;br /&gt;
The Spring framework uses a setter method to create this dependent object. Note the &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
       &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
    &amp;lt;/bean&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
   &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions from inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
 public class MyClient&lt;br /&gt;
 {&lt;br /&gt;
    public static void main(String args[])&lt;br /&gt;
        {&lt;br /&gt;
                Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
                BeanFactory factory =new XmlBeanFactory(res); &lt;br /&gt;
                //” doctorServiceId” is the same id defined in ApplicationContext.xml&lt;br /&gt;
                DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
         }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first the path for the ApplicationContext is specified, and then this file is used as a resource by the container. The BeanFactory container uses the xml file to access the bean defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However, Setter Injection unnecessarily adds to the abstraction. The developer needs to know which dependencies are needed when. On the other hand, it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;br /&gt;
&lt;br /&gt;
==Type 3- Constructor Injection==&lt;br /&gt;
&lt;br /&gt;
Constructor Injection is the DI technique of passing an object's dependencies to its constructor. It addresses the most common scenario where a class requires one or more Dependencies, and no reasonable local defaults are available.&lt;br /&gt;
&lt;br /&gt;
Constructor Injection addresses this scenario very well, because it guarantees that the Dependency is always present. If the depending class absolutely cannot function without the Dependency, such a guarantee is valuable. Constructor-injection enforces the order of initialization and prevents circular dependencies http://en.wikipedia.org/wiki/Circular_dependency. &lt;br /&gt;
On the other hand, with Setter injection, it is not clear, in which order things need to be instantiated. Apart from the guaranteed injection, this pattern is also very easy to implement. &lt;br /&gt;
&lt;br /&gt;
Continuing with the example mentioned above, we can implement the same using constructor injection as follows, &amp;lt;br&amp;gt; [[image:di_image3.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
      private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
    // constructor for instantiatng prescriptionDAO&lt;br /&gt;
      public DoctorService (prescriptionDAO)&lt;br /&gt;
         { &lt;br /&gt;
            this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
         }&lt;br /&gt;
 //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
 public void print()&lt;br /&gt;
         {	&lt;br /&gt;
               System.out.println(&amp;quot;prescription:&amp;quot; +prescriptionDAO.prescription);&lt;br /&gt;
               System.out.println(&amp;quot;dose: &amp;quot;+prescriptionDAO.dose); &lt;br /&gt;
         }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
In the example, you must have noticed the parametrized constructor which Spring framework uses to instantiate the value of prescriptionDAO. &lt;br /&gt;
Now, the question is- how Spring container will come to know whether it has to use Constructor injection or Setter Injection? Tags inside the &amp;lt;bean&amp;gt; tag will specify this:&lt;br /&gt;
* &amp;lt;property&amp;gt; tag   is used for Setter Injection&lt;br /&gt;
* &amp;lt;constructor-arg&amp;gt; is used for Constructor Injection.&lt;br /&gt;
&lt;br /&gt;
ApplicationContect.xml for Constructor injection will be:&lt;br /&gt;
 '''''ApplicationContect.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
                 &amp;lt;!-- constructor injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
 		 &amp;lt;constructor-arg&amp;gt;&lt;br /&gt;
                 &amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&lt;br /&gt;
                 &amp;lt;/constructor-arg&amp;gt;&lt;br /&gt;
   &amp;lt;/bean&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Definitions for PrescriptionDAO.java and MyClient.java will remain the same.&lt;br /&gt;
The advantage of using Constructor Injection is that it can create the objects at the time of instantiation itself. Hence it guarantees the developer, that the objects will definitely get created and no exception will be raised. However, unlike [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Type_2-_Setter_Injection Setter injection] it won’t allow changes to the dependency, once it is created.&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39843</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39843"/>
		<updated>2010-11-03T01:53:47Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: /* Type 3- Constructor Injection */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is a highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* '''Apache Avalon'''- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is a highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us consider a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object. We need some Assembler (DI Framework) to instantiate the Department field of Employee class. Rather than Employee class creating this object for itself, it will delegate this task of instantiation to any framework selected from above. To do this, it uses configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Types_of_Dependency_Injection section 4]. &lt;br /&gt;
&lt;br /&gt;
 '''''Employee.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''Department.java'''''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
The framework will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object. It will form an Employee object with a Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where the binding of beans is done as follows:&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, one only needs to update the configuration file. There is no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is a technique to add the dependency for interfaces in components at run time. The components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using the Avalon framework: ////////////////////////////////////////provide external link&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 '''''AccountApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 '''''CustomerApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface. The ApplicationServiceImpl class implements the ApplicationService inteface, which in turn implements the ApplicationDAO interface, provided by the container.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationServiceImpl.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container, which uses configuration file for look up, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
The Configuration File that will be used by MyClass file to lookup the dependency configurations will be of type:&lt;br /&gt;
&lt;br /&gt;
 '''''App.Config'''''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
In this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference. The getEntity() that is invoked will actually depend on the dependency that is injected via the configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state (variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us consider an example of Setter injection by using Spring Framework. [/////////////////////] Before using Spring, let us study some basic features of Spring. We will cover only a brief overview of the Spring Framework. For better understanding of Spring, please visit the site:  [ ////////////////////////////]&lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[ ], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
Now let us see Setter injection using the Spring framework.&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is the class on which DoctorService depends. &amp;lt;br&amp;gt;[[image:di_image2.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
           { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
           }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
           { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
            }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
            {&lt;br /&gt;
              System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
              System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
             }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
        private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
                return  this.prescription;&lt;br /&gt;
        }&lt;br /&gt;
        public void setPrescription(String prescription) &lt;br /&gt;
        {&lt;br /&gt;
           this. prescription = prescription;&lt;br /&gt;
         }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here, the invoking object is responsible for setting the PrescriptionDAO dependency. There is no code inside the class that is creating new instance of PrescriptionDAO. This is because this task will be performed by the Spring container, by looking for dependencies of DoctorService inside applicationContext.xml file.&lt;br /&gt;
&lt;br /&gt;
The Spring framework uses a setter method to create this dependent object. Note the &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
       &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
    &amp;lt;/bean&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
   &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions from inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
 public class MyClient&lt;br /&gt;
 {&lt;br /&gt;
    public static void main(String args[])&lt;br /&gt;
        {&lt;br /&gt;
                Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
                BeanFactory factory =new XmlBeanFactory(res); &lt;br /&gt;
                //” doctorServiceId” is the same id defined in ApplicationContext.xml&lt;br /&gt;
                DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
         }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first the path for the ApplicationContext is specified, and then this file is used as a resource by the container. The BeanFactory container uses the xml file to access the bean defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However, Setter Injection unnecessarily adds to the abstraction. The developer needs to know which dependencies are needed when. On the other hand, it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;br /&gt;
&lt;br /&gt;
==Type 3- Constructor Injection==&lt;br /&gt;
&lt;br /&gt;
Constructor Injection is the DI technique of passing an object's dependencies to its constructor. It addresses the most common scenario where a class requires one or more Dependencies, and no reasonable local defaults are available.&lt;br /&gt;
&lt;br /&gt;
Constructor Injection addresses this scenario very well, because it guarantees that the Dependency is always present. If the depending class absolutely cannot function without the Dependency, such a guarantee is valuable. Constructor-injection enforces the order of initialization and prevents circular dependencies http://en.wikipedia.org/wiki/Circular_dependency. &lt;br /&gt;
On the other hand, with Setter injection, it is not clear, in which order things need to be instantiated. Apart from the guaranteed injection, this pattern is also very easy to implement. &lt;br /&gt;
&lt;br /&gt;
Continuing with the example mentioned above, we can implement the same using constructor injection as follows, &amp;lt;br&amp;gt; [[image:di_image3.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
      private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
    // constructor for instantiatng prescriptionDAO&lt;br /&gt;
      public DoctorService (prescriptionDAO)&lt;br /&gt;
         { &lt;br /&gt;
            this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
         }&lt;br /&gt;
 //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
 public void print()&lt;br /&gt;
         {	&lt;br /&gt;
               System.out.println(&amp;quot;prescription:&amp;quot; +prescriptionDAO.prescription);&lt;br /&gt;
               System.out.println(&amp;quot;dose: &amp;quot;+prescriptionDAO.dose); &lt;br /&gt;
         }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
In the example, you must have noticed the parametrized constructor which Spring framework uses to instantiate the value of prescriptionDAO. &lt;br /&gt;
Now, the question is- how Spring container will come to know whether it has to use Constructor injection or Setter Injection? Tags inside the &amp;lt;bean&amp;gt; tag will specify this:&lt;br /&gt;
* &amp;lt;property&amp;gt; tag   is used for Setter Injection&lt;br /&gt;
* &amp;lt;constructor-arg&amp;gt; is used for Constructor Injection.&lt;br /&gt;
&lt;br /&gt;
ApplicationContect.xml for Constructor injection will be:&lt;br /&gt;
 '''''ApplicationContect.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
                                 &amp;lt;!-- constructor injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
 		 &amp;lt;constructor-arg&amp;gt;&lt;br /&gt;
                                       &amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&lt;br /&gt;
                                 &amp;lt;/constructor-arg&amp;gt;&lt;br /&gt;
   &amp;lt;/bean&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Definitions for PrescriptionDAO.java and MyClient.java will remain the same.&lt;br /&gt;
The advantage of using Constructor Injection is that it can create the objects at the time of instantiation itself. Hence it guarantees the developer, that the objects will definitely get created and no exception will be raised. However, unlike [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Type_2-_Setter_Injection Setter injection] it won’t allow changes to the dependency, once it is created.&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39842</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39842"/>
		<updated>2010-11-03T01:45:38Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: /* Type 3- Constructor Injection */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is a highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* '''Apache Avalon'''- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is a highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us consider a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object. We need some Assembler (DI Framework) to instantiate the Department field of Employee class. Rather than Employee class creating this object for itself, it will delegate this task of instantiation to any framework selected from above. To do this, it uses configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Types_of_Dependency_Injection section 4]. &lt;br /&gt;
&lt;br /&gt;
 '''''Employee.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''Department.java'''''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
The framework will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object. It will form an Employee object with a Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where the binding of beans is done as follows:&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, one only needs to update the configuration file. There is no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is a technique to add the dependency for interfaces in components at run time. The components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using the Avalon framework: ////////////////////////////////////////provide external link&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 '''''AccountApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 '''''CustomerApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface. The ApplicationServiceImpl class implements the ApplicationService inteface, which in turn implements the ApplicationDAO interface, provided by the container.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationServiceImpl.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container, which uses configuration file for look up, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
The Configuration File that will be used by MyClass file to lookup the dependency configurations will be of type:&lt;br /&gt;
&lt;br /&gt;
 '''''App.Config'''''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
In this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference. The getEntity() that is invoked will actually depend on the dependency that is injected via the configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state (variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us consider an example of Setter injection by using Spring Framework. [/////////////////////] Before using Spring, let us study some basic features of Spring. We will cover only a brief overview of the Spring Framework. For better understanding of Spring, please visit the site:  [ ////////////////////////////]&lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[ ], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
Now let us see Setter injection using the Spring framework.&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is the class on which DoctorService depends. &amp;lt;br&amp;gt;[[image:di_image2.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
           { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
           }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
           { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
            }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
            {&lt;br /&gt;
              System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
              System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
             }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
        private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
                return  this.prescription;&lt;br /&gt;
        }&lt;br /&gt;
        public void setPrescription(String prescription) &lt;br /&gt;
        {&lt;br /&gt;
           this. prescription = prescription;&lt;br /&gt;
         }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here, the invoking object is responsible for setting the PrescriptionDAO dependency. There is no code inside the class that is creating new instance of PrescriptionDAO. This is because this task will be performed by the Spring container, by looking for dependencies of DoctorService inside applicationContext.xml file.&lt;br /&gt;
&lt;br /&gt;
The Spring framework uses a setter method to create this dependent object. Note the &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
       &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
    &amp;lt;/bean&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
   &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions from inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
 public class MyClient&lt;br /&gt;
 {&lt;br /&gt;
    public static void main(String args[])&lt;br /&gt;
        {&lt;br /&gt;
                Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
                BeanFactory factory =new XmlBeanFactory(res); &lt;br /&gt;
                //” doctorServiceId” is the same id defined in ApplicationContext.xml&lt;br /&gt;
                DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
         }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first the path for the ApplicationContext is specified, and then this file is used as a resource by the container. The BeanFactory container uses the xml file to access the bean defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However, Setter Injection unnecessarily adds to the abstraction. The developer needs to know which dependencies are needed when. On the other hand, it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;br /&gt;
&lt;br /&gt;
==Type 3- Constructor Injection==&lt;br /&gt;
&lt;br /&gt;
Constructor Injection is the DI technique of passing an object's dependencies to its constructor. It addresses the most common scenario where a class requires one or more Dependencies, and no reasonable local defaults are available.&lt;br /&gt;
&lt;br /&gt;
Constructor Injection addresses this scenario very well, because it guarantees that the Dependency is always present. If the depending class absolutely cannot function without the Dependency, such a guarantee is valuable. Constructor-injection enforces the order of initialization and prevents circular dependencies http://en.wikipedia.org/wiki/Circular_dependency. &lt;br /&gt;
On the other hand, with Setter injection, it is not clear, in which order things need to be instantiated. Apart from the guaranteed injection, this pattern is also very easy to implement. &lt;br /&gt;
&lt;br /&gt;
Continuing with the example mentioned above, we can implement the same using constructor injection as follows, &amp;lt;br&amp;gt; [[image:di_image3.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
      private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
    // constructor for instantiatng prescriptionDAO&lt;br /&gt;
      public DoctorService (prescriptionDAO)&lt;br /&gt;
         { &lt;br /&gt;
            this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
         }&lt;br /&gt;
 //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
 public void print()&lt;br /&gt;
         {	&lt;br /&gt;
               System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
               System.out.println(“dose: “+prescriptionDAO.dose); &lt;br /&gt;
         }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
In the example, you must have noticed the parametrized constructor which Spring framework uses to instantiate the value of prescriptionDAO. &lt;br /&gt;
Now, the question is- how Spring container will come to know whether it has to use Constructor injection or Setter Injection? Tags inside the &amp;lt;bean&amp;gt; tag will specify this:&lt;br /&gt;
* &amp;lt;property&amp;gt; tag   is used for Setter Injection&lt;br /&gt;
* &amp;lt;constructor-arg&amp;gt; is used for Constructor Injection.&lt;br /&gt;
&lt;br /&gt;
ApplicationContect.xml for Constructor injection will be:&lt;br /&gt;
 '''''ApplicationContect.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
                                 &amp;lt;!-- constructor injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
 		 &amp;lt;constructor-arg&amp;gt;&lt;br /&gt;
                                       &amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&lt;br /&gt;
                                 &amp;lt;/constructor-arg&amp;gt;&lt;br /&gt;
   &amp;lt;/bean&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Definitions for PrescriptionDAO.java and MyClient.java will remain the same.&lt;br /&gt;
The advantage of using Constructor Injection is that it can create the objects at the time of instantiation itself. Hence it guarantees the developer, that the objects will definitely get created and no exception will be raised. However, unlike [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Type_2-_Setter_Injection Setter injection] it won’t allow changes to the dependency, once it is created.&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39831</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39831"/>
		<updated>2010-11-03T01:07:52Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is a highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* '''Apache Avalon'''- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is a highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us consider a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object. We need some Assembler (DI Framework) to instantiate the Department field of Employee class. Rather than Employee class creating this object for itself, it will delegate this task of instantiation to any framework selected from above. To do this, it uses configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Types_of_Dependency_Injection section 4]. &lt;br /&gt;
&lt;br /&gt;
 '''''Employee.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''Department.java'''''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
The framework will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object. It will form an Employee object with a Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where the binding of beans is done as follows:&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, one only needs to update the configuration file. There is no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is a technique to add the dependency for interfaces in components at run time. The components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using the Avalon framework: ////////////////////////////////////////provide external link&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 '''''AccountApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 '''''CustomerApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface. The ApplicationServiceImpl class implements the ApplicationService inteface, which in turn implements the ApplicationDAO interface, provided by the container.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationServiceImpl.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container, which uses configuration file for look up, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
The Configuration File that will be used by MyClass file to lookup the dependency configurations will be of type:&lt;br /&gt;
&lt;br /&gt;
 '''''App.Config'''''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
In this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference. The getEntity() that is invoked will actually depend on the dependency that is injected via the configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state (variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us consider an example of Setter injection by using Spring Framework. [/////////////////////] Before using Spring, let us study some basic features of Spring. We will cover only a brief overview of the Spring Framework. For better understanding of Spring, please visit the site:  [ ////////////////////////////]&lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[ ], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
Now let us see Setter injection using the Spring framework.&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is the class on which DoctorService depends. &amp;lt;br&amp;gt;[[image:di_image2.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
           { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
           }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
           { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
            }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
            {&lt;br /&gt;
              System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
              System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
             }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
        private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
                return  this.prescription;&lt;br /&gt;
        }&lt;br /&gt;
        public void setPrescription(String prescription) &lt;br /&gt;
        {&lt;br /&gt;
           this. prescription = prescription;&lt;br /&gt;
         }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here, the invoking object is responsible for setting the PrescriptionDAO dependency. There is no code inside the class that is creating new instance of PrescriptionDAO. This is because this task will be performed by the Spring container, by looking for dependencies of DoctorService inside applicationContext.xml file.&lt;br /&gt;
&lt;br /&gt;
The Spring framework uses a setter method to create this dependent object. Note the &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
       &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
    &amp;lt;/bean&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
       &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
   &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions from inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
 public class MyClient&lt;br /&gt;
 {&lt;br /&gt;
    public static void main(String args[])&lt;br /&gt;
        {&lt;br /&gt;
                Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
                BeanFactory factory =new XmlBeanFactory(res); &lt;br /&gt;
                //” doctorServiceId” is the same id defined in ApplicationContext.xml&lt;br /&gt;
                DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
         }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first the path for the ApplicationContext is specified, and then this file is used as a resource by the container. The BeanFactory container uses the xml file to access the bean defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However, Setter Injection unnecessarily adds to the abstraction. The developer needs to know which dependencies are needed when. On the other hand, it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;br /&gt;
&lt;br /&gt;
==Type 3- Constructor Injection==&lt;br /&gt;
&lt;br /&gt;
Constructor Injection is the DI technique of passing an object's dependencies to its constructor. It addresses the most common scenario where a class requires one or more Dependencies, and no reasonable local defaults are available.&lt;br /&gt;
&lt;br /&gt;
Constructor Injection addresses this scenario very well, because it guarantees that the Dependency is always present. If the depending class absolutely cannot function without the Dependency, such a guarantee is valuable. Constructor-injection enforces the order of initialization and prevents circular dependencies http://en.wikipedia.org/wiki/Circular_dependency. &lt;br /&gt;
On the other hand, with Setter injection, it is not clear, in which order things need to be instantiated. Apart from the guaranteed injection, this pattern is also very easy to implement. &lt;br /&gt;
&lt;br /&gt;
Continuing with the example mentioned above, we can implement the same using constructor injection as follows, &amp;lt;br. [[image:di_image3.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
      private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
    // constructor for instantiatng prescriptionDAO&lt;br /&gt;
      public DoctorService (prescriptionDAO)&lt;br /&gt;
         { &lt;br /&gt;
            this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
         }&lt;br /&gt;
 //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
 public void print()&lt;br /&gt;
         {	&lt;br /&gt;
               System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
               System.out.println(“dose: “+prescriptionDAO.dose); &lt;br /&gt;
         }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
In the example, you must have noticed the parametrized constructor which Spring framework uses to instantiate the value of prescriptionDAO. &lt;br /&gt;
Now, the question is- how Spring container will come to know whether it has to use Constructor injection or Setter Injection? Tags inside the &amp;lt;bean&amp;gt; tag will specify this:&lt;br /&gt;
* &amp;lt;property&amp;gt; tag   is used for Setter Injection&lt;br /&gt;
* &amp;lt;constructor-arg&amp;gt; is used for Constructor Injection.&lt;br /&gt;
&lt;br /&gt;
ApplicationContect.xml for Constructor injection will be:&lt;br /&gt;
 '''''ApplicationContect.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
                                 &amp;lt;!-- constructor injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
 		 &amp;lt;constructor-arg&amp;gt;&lt;br /&gt;
                                       &amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&lt;br /&gt;
                                 &amp;lt;/constructor-arg&amp;gt;&lt;br /&gt;
   &amp;lt;/bean&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Definitions for PrescriptionDAO.java and MyClient.java will remain the same.&lt;br /&gt;
The advantage of using Constructor Injection is that it can create the objects at the time of instantiation itself. Hence it guarantees the developer, that the objects will definitely get created and no exception will be raised. However, unlike [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Type_2-_Setter_Injection Setter injection] it won’t allow changes to the dependency, once it is created.&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39826</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39826"/>
		<updated>2010-11-03T00:43:17Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is a highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* '''Apache Avalon'''- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is a highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us consider a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object. We need some Assembler (DI Framework) to instantiate the Department field of Employee class. Rather than Employee class creating this object for itself, it will delegate this task of instantiation to any framework selected from above. To do this, it uses configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch5_5e_dr#Types_of_Dependency_Injection section 4]. &lt;br /&gt;
&lt;br /&gt;
 '''''Employee.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''Department.java'''''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, we only need to update our configuration file. There is  no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write the loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is the technique to add the dependency for interfaces in the components at run time, and components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using Avalon framework:&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 '''''AccountApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 '''''CustomerApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface, and we have ApplicationServiceImpl class(component) implementing the ApplicationService inteface, which will do the specific implementation of the ApplicationDAO  interface provided by the container as per the configuration.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationServiceImpl.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container which use configuration file for lookup, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
Configuration File that will be used by MyClass file to lookup the dependency configurations.&lt;br /&gt;
&lt;br /&gt;
 '''''App.Config'''''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Here, in this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference, and which getEntity() is invoked (of Accoun ot Customer ) actually depends on the dependency that is injected via configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state (variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us take an example of Setter injection by using Spring Framework. [] Before using Spring, let us study some basic features of Springs. We are not including detailed explanation and complicacies of Springs here, for better understanding you can visit the site:  [ ]&lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[ ], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will see Setter and Constructor Injection using Spring Framework.&lt;br /&gt;
&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is a class on which DoctorService depends. &amp;lt;br&amp;gt;[[image:di_image2.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
           { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
           }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
           { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
            }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
            {&lt;br /&gt;
              System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
              System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
             }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
        private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
                return  this.prescription;&lt;br /&gt;
        }&lt;br /&gt;
        public void setPrescription(String prescription) &lt;br /&gt;
        {&lt;br /&gt;
           this. prescription = prescription;&lt;br /&gt;
         }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above example, the invoking object is responsible for setting the PrescriptionDAO dependency. Now there is no code inside the class that is creating new instance of PrescriptionDAO, because this will be done by the Spring container by looking for dependencies of DoctorService inside applicationContext.xml file, which is usually stired in WEB-INF folder of web application&lt;br /&gt;
&lt;br /&gt;
Spring framework uses setter method to create this dependent object, and note the  &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
For Constructor injection, it uses another tag, &amp;lt;constructor-arg&amp;gt;, we will refer to it later.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
  &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
 &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions defined inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
 public class MyClient&lt;br /&gt;
 {&lt;br /&gt;
    public static void main(String args[])&lt;br /&gt;
        {&lt;br /&gt;
                Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
                BeanFactory factory =new XmlBeanFactory(res); &lt;br /&gt;
                //” doctorServiceId” is the same id defined in ApplicationContext.xml&lt;br /&gt;
                DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
         }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first path for the ApplicationContext is given and this file is used a s resource by the container.  BeanFactory(or Container) uses this xml file to get the bean we defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However Setter Injection adds the abstraction for the developer to know which dependencies are needed when. But it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;br /&gt;
&lt;br /&gt;
==Type 3- Constructor Injection==&lt;br /&gt;
&lt;br /&gt;
Constructor Injection is the DI technique of passing an object's dependencies to its constructor. It addresses the most common scenario where a class requires one or more Dependencies, and no reasonable local defaults are available.&lt;br /&gt;
&lt;br /&gt;
Constructor Injection addresses that scenario very well because it guarantees that the Dependency is always present. If the depending class absolutely cannot function without the Dependency, that guarantee is valuable. Constructor-injection enforces the order of initialization and prevents circular dependencies http://en.wikipedia.org/wiki/Circular_dependency. &lt;br /&gt;
On the other hand, with setter-injection it is not clear in which order things need to be instantiated. Apart from the guaranteed injection, this pattern is also very easy to implement. &lt;br /&gt;
&lt;br /&gt;
Continuing with the example mentioned above, we can implement the same using constructor injection as follows, &amp;lt;br. [[image:di_image3.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
      private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
    // constructor for instantiatng prescriptionDAO&lt;br /&gt;
      public DoctorService (prescriptionDAO)&lt;br /&gt;
         { &lt;br /&gt;
            this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
         }&lt;br /&gt;
 //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
 public void print()&lt;br /&gt;
         {	&lt;br /&gt;
               System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
               System.out.println(“dose: “+prescriptionDAO.dose); &lt;br /&gt;
         }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
In the example, you must have noticed the parameterized constructor which Spring framework will use to instantiate the value of prescriptionDAO. &lt;br /&gt;
Now, question is that how Spring container will come to know whether it has to use Constructor injection or Setter Injection. Tags inside the &amp;lt;bean&amp;gt; tag will specify this:&lt;br /&gt;
* &amp;lt;property&amp;gt; tag   is used for Setter Injection&lt;br /&gt;
* &amp;lt;constructor-arg&amp;gt; is used for Constructor Injection.&lt;br /&gt;
&lt;br /&gt;
ApplicationContect.xml for Constructor injection will be:&lt;br /&gt;
 '''''ApplicationContect.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
                                 &amp;lt;!-- constructor injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
 		 &amp;lt;constructor-arg&amp;gt;&lt;br /&gt;
                                       &amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&lt;br /&gt;
                                 &amp;lt;/constructor-arg&amp;gt;&lt;br /&gt;
   &amp;lt;/bean&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Definitions for PrescriptionDAO.java and MyClient.java will remain same.&lt;br /&gt;
The advantage of using Constructor Injection is that it can create the objects at the time of instantiation itself and hence guarantee the developer that objects will definitely get created and no exception will be raised , but it won’t allow to change the dependency once created. This we can achieve by using Setter injection, calling setter method at any future point of time.&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39824</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39824"/>
		<updated>2010-11-03T00:38:12Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 '''''Employee.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''Department.java'''''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, we only need to update our configuration file. There is  no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write the loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is the technique to add the dependency for interfaces in the components at run time, and components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using Avalon framework:&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 '''''AccountApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 '''''CustomerApplicationDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface, and we have ApplicationServiceImpl class(component) implementing the ApplicationService inteface, which will do the specific implementation of the ApplicationDAO  interface provided by the container as per the configuration.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationServiceImpl.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container which use configuration file for lookup, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
Configuration File that will be used by MyClass file to lookup the dependency configurations.&lt;br /&gt;
&lt;br /&gt;
 '''''App.Config'''''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Here, in this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference, and which getEntity() is invoked (of Accoun ot Customer ) actually depends on the dependency that is injected via configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state (variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us take an example of Setter injection by using Spring Framework. [] Before using Spring, let us study some basic features of Springs. We are not including detailed explanation and complicacies of Springs here, for better understanding you can visit the site:  [ ]&lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[ ], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will see Setter and Constructor Injection using Spring Framework.&lt;br /&gt;
&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is a class on which DoctorService depends. &amp;lt;br&amp;gt;[[image:di_image2.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
           { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
           }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
           { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
            }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
            {&lt;br /&gt;
              System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
              System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
             }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
        private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
                return  this.prescription;&lt;br /&gt;
        }&lt;br /&gt;
        public void setPrescription(String prescription) &lt;br /&gt;
        {&lt;br /&gt;
           this. prescription = prescription;&lt;br /&gt;
         }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above example, the invoking object is responsible for setting the PrescriptionDAO dependency. Now there is no code inside the class that is creating new instance of PrescriptionDAO, because this will be done by the Spring container by looking for dependencies of DoctorService inside applicationContext.xml file, which is usually stired in WEB-INF folder of web application&lt;br /&gt;
&lt;br /&gt;
Spring framework uses setter method to create this dependent object, and note the  &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
For Constructor injection, it uses another tag, &amp;lt;constructor-arg&amp;gt;, we will refer to it later.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
  &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
 &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions defined inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
 public class MyClient&lt;br /&gt;
 {&lt;br /&gt;
    public static void main(String args[])&lt;br /&gt;
        {&lt;br /&gt;
                Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
                BeanFactory factory =new XmlBeanFactory(res); &lt;br /&gt;
                //” doctorServiceId” is the same id defined in ApplicationContext.xml&lt;br /&gt;
                DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
         }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first path for the ApplicationContext is given and this file is used a s resource by the container.  BeanFactory(or Container) uses this xml file to get the bean we defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However Setter Injection adds the abstraction for the developer to know which dependencies are needed when. But it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;br /&gt;
&lt;br /&gt;
==Type 3- Constructor Injection==&lt;br /&gt;
&lt;br /&gt;
Constructor Injection is the DI technique of passing an object's dependencies to its constructor. It addresses the most common scenario where a class requires one or more Dependencies, and no reasonable local defaults are available.&lt;br /&gt;
&lt;br /&gt;
Constructor Injection addresses that scenario very well because it guarantees that the Dependency is always present. If the depending class absolutely cannot function without the Dependency, that guarantee is valuable. Constructor-injection enforces the order of initialization and prevents circular dependencies http://en.wikipedia.org/wiki/Circular_dependency. &lt;br /&gt;
On the other hand, with setter-injection it is not clear in which order things need to be instantiated. Apart from the guaranteed injection, this pattern is also very easy to implement. &lt;br /&gt;
&lt;br /&gt;
Continuing with the example mentioned above, we can implement the same using constructor injection as follows, &amp;lt;br. [[image:di_image3.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
      private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
    // constructor for instantiatng prescriptionDAO&lt;br /&gt;
      public DoctorService (prescriptionDAO)&lt;br /&gt;
         { &lt;br /&gt;
            this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
         }&lt;br /&gt;
 //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
 public void print()&lt;br /&gt;
         {	&lt;br /&gt;
               System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
               System.out.println(“dose: “+prescriptionDAO.dose); &lt;br /&gt;
         }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
In the example, you must have noticed the parameterized constructor which Spring framework will use to instantiate the value of prescriptionDAO. &lt;br /&gt;
Now, question is that how Spring container will come to know whether it has to use Constructor injection or Setter Injection. Tags inside the &amp;lt;bean&amp;gt; tag will specify this:&lt;br /&gt;
* &amp;lt;property&amp;gt; tag   is used for Setter Injection&lt;br /&gt;
* &amp;lt;constructor-arg&amp;gt; is used for Constructor Injection.&lt;br /&gt;
&lt;br /&gt;
ApplicationContect.xml for Constructor injection will be:&lt;br /&gt;
 '''''ApplicationContect.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
                                 &amp;lt;!-- constructor injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
 		 &amp;lt;constructor-arg&amp;gt;&lt;br /&gt;
                                       &amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&lt;br /&gt;
                                 &amp;lt;/constructor-arg&amp;gt;&lt;br /&gt;
   &amp;lt;/bean&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Definitions for PrescriptionDAO.java and MyClient.java will remain same.&lt;br /&gt;
The advantage of using Constructor Injection is that it can create the objects at the time of instantiation itself and hence guarantee the developer that objects will definitely get created and no exception will be raised , but it won’t allow to change the dependency once created. This we can achieve by using Setter injection, calling setter method at any future point of time.&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39822</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39822"/>
		<updated>2010-11-03T00:36:29Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 ''''' Employee.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''Department.java'''''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, we only need to update our configuration file. There is  no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write the loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is the technique to add the dependency for interfaces in the components at run time, and components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using Avalon framework:&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 ''ApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 ''AccountApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 ''CustomerApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface, and we have ApplicationServiceImpl class(component) implementing the ApplicationService inteface, which will do the specific implementation of the ApplicationDAO  interface provided by the container as per the configuration.&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationService.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationServiceImpl.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container which use configuration file for lookup, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
Configuration File that will be used by MyClass file to lookup the dependency configurations.&lt;br /&gt;
&lt;br /&gt;
 ''App.Config''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Here, in this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference, and which getEntity() is invoked (of Accoun ot Customer ) actually depends on the dependency that is injected via configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state (variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us take an example of Setter injection by using Spring Framework. [] Before using Spring, let us study some basic features of Springs. We are not including detailed explanation and complicacies of Springs here, for better understanding you can visit the site:  [ ]&lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[ ], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will see Setter and Constructor Injection using Spring Framework.&lt;br /&gt;
&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is a class on which DoctorService depends. &amp;lt;br&amp;gt;[[image:di_image2.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
           { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
           }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
           { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
            }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
            {&lt;br /&gt;
              System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
              System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
             }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
        private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
                return  this.prescription;&lt;br /&gt;
        }&lt;br /&gt;
        public void setPrescription(String prescription) &lt;br /&gt;
        {&lt;br /&gt;
           this. prescription = prescription;&lt;br /&gt;
         }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above example, the invoking object is responsible for setting the PrescriptionDAO dependency. Now there is no code inside the class that is creating new instance of PrescriptionDAO, because this will be done by the Spring container by looking for dependencies of DoctorService inside applicationContext.xml file, which is usually stired in WEB-INF folder of web application&lt;br /&gt;
&lt;br /&gt;
Spring framework uses setter method to create this dependent object, and note the  &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
For Constructor injection, it uses another tag, &amp;lt;constructor-arg&amp;gt;, we will refer to it later.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
  &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
 &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions defined inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
 public class MyClient&lt;br /&gt;
 {&lt;br /&gt;
    public static void main(String args[])&lt;br /&gt;
        {&lt;br /&gt;
                Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
                BeanFactory factory =new XmlBeanFactory(res); &lt;br /&gt;
                //” doctorServiceId” is the same id defined in ApplicationContext.xml&lt;br /&gt;
                DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
         }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first path for the ApplicationContext is given and this file is used a s resource by the container.  BeanFactory(or Container) uses this xml file to get the bean we defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However Setter Injection adds the abstraction for the developer to know which dependencies are needed when. But it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;br /&gt;
&lt;br /&gt;
==Type 3- Constructor Injection==&lt;br /&gt;
&lt;br /&gt;
Constructor Injection is the DI technique of passing an object's dependencies to its constructor. It addresses the most common scenario where a class requires one or more Dependencies, and no reasonable local defaults are available.&lt;br /&gt;
&lt;br /&gt;
Constructor Injection addresses that scenario very well because it guarantees that the Dependency is always present. If the depending class absolutely cannot function without the Dependency, that guarantee is valuable. Constructor-injection enforces the order of initialization and prevents circular dependencies http://en.wikipedia.org/wiki/Circular_dependency. &lt;br /&gt;
On the other hand, with setter-injection it is not clear in which order things need to be instantiated. Apart from the guaranteed injection, this pattern is also very easy to implement. &lt;br /&gt;
&lt;br /&gt;
Continuing with the example mentioned above, we can implement the same using constructor injection as follows, &amp;lt;br. [[image:di_image3.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
      private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
    // constructor for instantiatng prescriptionDAO&lt;br /&gt;
      public DoctorService (prescriptionDAO)&lt;br /&gt;
         { &lt;br /&gt;
            this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
         }&lt;br /&gt;
 //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
 public void print()&lt;br /&gt;
         {	&lt;br /&gt;
               System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
               System.out.println(“dose: “+prescriptionDAO.dose); &lt;br /&gt;
         }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
In the example, you must have noticed the parameterized constructor which Spring framework will use to instantiate the value of prescriptionDAO. &lt;br /&gt;
Now, question is that how Spring container will come to know whether it has to use Constructor injection or Setter Injection. Tags inside the &amp;lt;bean&amp;gt; tag will specify this:&lt;br /&gt;
* &amp;lt;property&amp;gt; tag   is used for Setter Injection&lt;br /&gt;
* &amp;lt;constructor-arg&amp;gt; is used for Constructor Injection.&lt;br /&gt;
&lt;br /&gt;
ApplicationContect.xml for Constructor injection will be:&lt;br /&gt;
 '''''ApplicationContect.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
                                 &amp;lt;!-- constructor injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
 		 &amp;lt;constructor-arg&amp;gt;&lt;br /&gt;
                                       &amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&lt;br /&gt;
                                 &amp;lt;/constructor-arg&amp;gt;&lt;br /&gt;
   &amp;lt;/bean&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Definitions for PrescriptionDAO.java and MyClient.java will remain same.&lt;br /&gt;
The advantage of using Constructor Injection is that it can create the objects at the time of instantiation itself and hence guarantee the developer that objects will definitely get created and no exception will be raised , but it won’t allow to change the dependency once created. This we can achieve by using Setter injection, calling setter method at any future point of time.&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39821</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39821"/>
		<updated>2010-11-03T00:35:15Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 ''''' Employee.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''Department.java'''''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, we only need to update our configuration file. There is  no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write the loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is the technique to add the dependency for interfaces in the components at run time, and components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using Avalon framework:&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 ''ApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 ''AccountApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 ''CustomerApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface, and we have ApplicationServiceImpl class(component) implementing the ApplicationService inteface, which will do the specific implementation of the ApplicationDAO  interface provided by the container as per the configuration.&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationService.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationServiceImpl.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container which use configuration file for lookup, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
Configuration File that will be used by MyClass file to lookup the dependency configurations.&lt;br /&gt;
&lt;br /&gt;
 ''App.Config''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Here, in this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference, and which getEntity() is invoked (of Accoun ot Customer ) actually depends on the dependency that is injected via configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state (variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us take an example of Setter injection by using Spring Framework. [] Before using Spring, let us study some basic features of Springs. We are not including detailed explanation and complicacies of Springs here, for better understanding you can visit the site:  [ ]&lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[ ], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will see Setter and Constructor Injection using Spring Framework.&lt;br /&gt;
&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is a class on which DoctorService depends. &amp;lt;br&amp;gt;[[image:di_image2.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
           { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
           }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
           { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
            }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
            {&lt;br /&gt;
              System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
              System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
             }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
        private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
                return  this.prescription;&lt;br /&gt;
        }&lt;br /&gt;
        public void setPrescription(String prescription) &lt;br /&gt;
        {&lt;br /&gt;
           this. prescription = prescription;&lt;br /&gt;
         }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above example, the invoking object is responsible for setting the PrescriptionDAO dependency. Now there is no code inside the class that is creating new instance of PrescriptionDAO, because this will be done by the Spring container by looking for dependencies of DoctorService inside applicationContext.xml file, which is usually stired in WEB-INF folder of web application&lt;br /&gt;
&lt;br /&gt;
Spring framework uses setter method to create this dependent object, and note the  &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
For Constructor injection, it uses another tag, &amp;lt;constructor-arg&amp;gt;, we will refer to it later.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
  &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
 &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions defined inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
 public class MyClient&lt;br /&gt;
 {&lt;br /&gt;
    public static void main(String args[])&lt;br /&gt;
        {&lt;br /&gt;
                Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
                BeanFactory factory =new XmlBeanFactory(res); &lt;br /&gt;
                //” doctorServiceId” is the same id defined in ApplicationContext.xml&lt;br /&gt;
                DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
         }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first path for the ApplicationContext is given and this file is used a s resource by the container.  BeanFactory(or Container) uses this xml file to get the bean we defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However Setter Injection adds the abstraction for the developer to know which dependencies are needed when. But it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;br /&gt;
&lt;br /&gt;
==Type 3- Constructor Injection==&lt;br /&gt;
&lt;br /&gt;
Constructor Injection is the DI technique of passing an object's dependencies to its constructor. It addresses the most common scenario where a class requires one or more Dependencies, and no reasonable local defaults are available.&lt;br /&gt;
&lt;br /&gt;
Constructor Injection addresses that scenario very well because it guarantees that the Dependency is always present. If the depending class absolutely cannot function without the Dependency, that guarantee is valuable. Constructor-injection enforces the order of initialization and prevents circular dependencies http://en.wikipedia.org/wiki/Circular_dependency. &lt;br /&gt;
On the other hand, with setter-injection it is not clear in which order things need to be instantiated. Apart from the guaranteed injection, this pattern is also very easy to implement. &lt;br /&gt;
&lt;br /&gt;
Continuing with the example mentioned above, we can implement the same using constructor injection as follows, &amp;lt;br. [[image:di_image3.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
      private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
    // constructor for instantiatng prescriptionDAO&lt;br /&gt;
      public DoctorService (prescriptionDAO)&lt;br /&gt;
         { &lt;br /&gt;
            this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
         }&lt;br /&gt;
 //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
 public void print()&lt;br /&gt;
         {	&lt;br /&gt;
               System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
               System.out.println(“dose: “+prescriptionDAO.dose); &lt;br /&gt;
         }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
In the example, you must have noticed the parameterized constructor which Spring framework will use to instantiate the value of prescriptionDAO. &lt;br /&gt;
Now, question is that how Spring container will come to know whether it has to use Constructor injection or Setter Injection. Tags inside the &amp;lt;bean&amp;gt; tag will specify this:&lt;br /&gt;
* &amp;lt;property&amp;gt; tag   is used for Setter Injection&lt;br /&gt;
* &amp;lt;constructor-arg&amp;gt; is used for Constructor Injection.&lt;br /&gt;
&lt;br /&gt;
ApplicationContect.xml for Constructor injection will be:&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
                                 &amp;lt;!-- constructor injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
 		 &amp;lt;constructor-arg&amp;gt;&lt;br /&gt;
                                       &amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&lt;br /&gt;
                                 &amp;lt;/constructor-arg&amp;gt;&lt;br /&gt;
   &amp;lt;/bean&amp;gt;&lt;br /&gt;
   &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
         &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
    &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39819</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39819"/>
		<updated>2010-11-03T00:32:31Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 ''''' Employee.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''Department.java'''''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, we only need to update our configuration file. There is  no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write the loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is the technique to add the dependency for interfaces in the components at run time, and components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using Avalon framework:&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 ''ApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 ''AccountApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 ''CustomerApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface, and we have ApplicationServiceImpl class(component) implementing the ApplicationService inteface, which will do the specific implementation of the ApplicationDAO  interface provided by the container as per the configuration.&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationService.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationServiceImpl.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container which use configuration file for lookup, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
Configuration File that will be used by MyClass file to lookup the dependency configurations.&lt;br /&gt;
&lt;br /&gt;
 ''App.Config''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Here, in this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference, and which getEntity() is invoked (of Accoun ot Customer ) actually depends on the dependency that is injected via configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state (variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us take an example of Setter injection by using Spring Framework. [] Before using Spring, let us study some basic features of Springs. We are not including detailed explanation and complicacies of Springs here, for better understanding you can visit the site:  [ ]&lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[ ], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will see Setter and Constructor Injection using Spring Framework.&lt;br /&gt;
&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is a class on which DoctorService depends. &amp;lt;br&amp;gt;[[image:di_image2.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
           { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
           }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
           { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
            }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
            {&lt;br /&gt;
              System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
              System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
             }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
        private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
                return  this.prescription;&lt;br /&gt;
        }&lt;br /&gt;
        public void setPrescription(String prescription) &lt;br /&gt;
        {&lt;br /&gt;
           this. prescription = prescription;&lt;br /&gt;
         }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above example, the invoking object is responsible for setting the PrescriptionDAO dependency. Now there is no code inside the class that is creating new instance of PrescriptionDAO, because this will be done by the Spring container by looking for dependencies of DoctorService inside applicationContext.xml file, which is usually stired in WEB-INF folder of web application&lt;br /&gt;
&lt;br /&gt;
Spring framework uses setter method to create this dependent object, and note the  &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
For Constructor injection, it uses another tag, &amp;lt;constructor-arg&amp;gt;, we will refer to it later.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
  &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
 &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions defined inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
 public class MyClient&lt;br /&gt;
 {&lt;br /&gt;
    public static void main(String args[])&lt;br /&gt;
        {&lt;br /&gt;
                Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
                BeanFactory factory =new XmlBeanFactory(res); &lt;br /&gt;
                //” doctorServiceId” is the same id defined in ApplicationContext.xml&lt;br /&gt;
                DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
         }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first path for the ApplicationContext is given and this file is used a s resource by the container.  BeanFactory(or Container) uses this xml file to get the bean we defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However Setter Injection adds the abstraction for the developer to know which dependencies are needed when. But it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;br /&gt;
&lt;br /&gt;
==Type 3- Constructor Injection==&lt;br /&gt;
&lt;br /&gt;
Constructor Injection is the DI technique of passing an object's dependencies to its constructor. It addresses the most common scenario where a class requires one or more Dependencies, and no reasonable local defaults are available.&lt;br /&gt;
&lt;br /&gt;
Constructor Injection addresses that scenario very well because it guarantees that the Dependency is always present. If the depending class absolutely cannot function without the Dependency, that guarantee is valuable. Constructor-injection enforces the order of initialization and prevents circular dependencies http://en.wikipedia.org/wiki/Circular_dependency. &lt;br /&gt;
On the other hand, with setter-injection it is not clear in which order things need to be instantiated. Apart from the guaranteed injection, this pattern is also very easy to implement. &lt;br /&gt;
&lt;br /&gt;
Continuing with the example mentioned above, we can implement the same using constructor injection as follows, &amp;lt;br. [[image:di_image3.png]] &amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
      private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
    // constructor for instantiatng prescriptionDAO&lt;br /&gt;
      public DoctorService (prescriptionDAO)&lt;br /&gt;
         { &lt;br /&gt;
            this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
         }&lt;br /&gt;
 //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
 public void print()&lt;br /&gt;
         {	&lt;br /&gt;
               System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
               System.out.println(“dose: “+prescriptionDAO.dose); &lt;br /&gt;
         }&lt;br /&gt;
   }&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Di_image3.png&amp;diff=39818</id>
		<title>File:Di image3.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Di_image3.png&amp;diff=39818"/>
		<updated>2010-11-03T00:29:15Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: Dependency Injection image1&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Dependency Injection image1&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Di_image2.png&amp;diff=39817</id>
		<title>File:Di image2.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Di_image2.png&amp;diff=39817"/>
		<updated>2010-11-03T00:26:33Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: Dependency Injection image1&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Dependency Injection image1&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39816</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39816"/>
		<updated>2010-11-03T00:25:57Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 '' Employee.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 ''Department.java''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationContext.xml''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, we only need to update our configuration file. There is  no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write the loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is the technique to add the dependency for interfaces in the components at run time, and components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using Avalon framework:&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 ''ApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 ''AccountApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 ''CustomerApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface, and we have ApplicationServiceImpl class(component) implementing the ApplicationService inteface, which will do the specific implementation of the ApplicationDAO  interface provided by the container as per the configuration.&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationService.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationServiceImpl.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container which use configuration file for lookup, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
Configuration File that will be used by MyClass file to lookup the dependency configurations.&lt;br /&gt;
&lt;br /&gt;
 ''App.Config''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Here, in this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference, and which getEntity() is invoked (of Accoun ot Customer ) actually depends on the dependency that is injected via configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state (variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us take an example of Setter injection by using Spring Framework. [] Before using Spring, let us study some basic features of Springs. We are not including detailed explanation and complicacies of Springs here, for better understanding you can visit the site:  [ ]&lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[ ], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will see Setter and Constructor Injection using Spring Framework.&lt;br /&gt;
&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is a class on which DoctorService depends. [[image:di_image2.png]]&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
           { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
           }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
           { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
            }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
            {&lt;br /&gt;
              System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
              System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
             }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
        private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
                return  this.prescription;&lt;br /&gt;
        }&lt;br /&gt;
        public void setPrescription(String prescription) &lt;br /&gt;
        {&lt;br /&gt;
           this. prescription = prescription;&lt;br /&gt;
         }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above example, the invoking object is responsible for setting the PrescriptionDAO dependency. Now there is no code inside the class that is creating new instance of PrescriptionDAO, because this will be done by the Spring container by looking for dependencies of DoctorService inside applicationContext.xml file, which is usually stired in WEB-INF folder of web application&lt;br /&gt;
&lt;br /&gt;
Spring framework uses setter method to create this dependent object, and note the  &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
For Constructor injection, it uses another tag, &amp;lt;constructor-arg&amp;gt;, we will refer to it later.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
  &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
 &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions defined inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
 public class MyClient&lt;br /&gt;
 {&lt;br /&gt;
    public static void main(String args[])&lt;br /&gt;
        {&lt;br /&gt;
                Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
                BeanFactory factory =new XmlBeanFactory(res); &lt;br /&gt;
                //” doctorServiceId” is the same id defined in ApplicationContext.xml&lt;br /&gt;
                DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
         }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first path for the ApplicationContext is given and this file is used a s resource by the container.  BeanFactory(or Container) uses this xml file to get the bean we defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However Setter Injection adds the abstraction for the developer to know which dependencies are needed when. But it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39814</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39814"/>
		<updated>2010-11-03T00:22:42Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 '' Employee.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 ''Department.java''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationContext.xml''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, we only need to update our configuration file. There is  no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write the loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is the technique to add the dependency for interfaces in the components at run time, and components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using Avalon framework:&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 ''ApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 ''AccountApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 ''CustomerApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface, and we have ApplicationServiceImpl class(component) implementing the ApplicationService inteface, which will do the specific implementation of the ApplicationDAO  interface provided by the container as per the configuration.&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationService.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationServiceImpl.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container which use configuration file for lookup, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
Configuration File that will be used by MyClass file to lookup the dependency configurations.&lt;br /&gt;
&lt;br /&gt;
 ''App.Config''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Here, in this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference, and which getEntity() is invoked (of Accoun ot Customer ) actually depends on the dependency that is injected via configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state (variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us take an example of Setter injection by using Spring Framework. [] Before using Spring, let us study some basic features of Springs. We are not including detailed explanation and complicacies of Springs here, for better understanding you can visit the site:  [ ]&lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[ ], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will see Setter and Constructor Injection using Spring Framework.&lt;br /&gt;
&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is a class on which DoctorService depends.&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
           { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
           }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
           { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
            }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
            {&lt;br /&gt;
              System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
              System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
             }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
        private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
                return  this.prescription;&lt;br /&gt;
        }&lt;br /&gt;
        public void setPrescription(String prescription) &lt;br /&gt;
        {&lt;br /&gt;
           this. prescription = prescription;&lt;br /&gt;
         }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above example, the invoking object is responsible for setting the PrescriptionDAO dependency. Now there is no code inside the class that is creating new instance of PrescriptionDAO, because this will be done by the Spring container by looking for dependencies of DoctorService inside applicationContext.xml file, which is usually stired in WEB-INF folder of web application&lt;br /&gt;
&lt;br /&gt;
Spring framework uses setter method to create this dependent object, and note the  &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
For Constructor injection, it uses another tag, &amp;lt;constructor-arg&amp;gt;, we will refer to it later.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
  &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
 &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions defined inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
 public class MyClient&lt;br /&gt;
 {&lt;br /&gt;
    public static void main(String args[])&lt;br /&gt;
        {&lt;br /&gt;
                Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
                BeanFactory factory =new XmlBeanFactory(res); &lt;br /&gt;
                //” doctorServiceId” is the same id defined in ApplicationContext.xml&lt;br /&gt;
        	DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
         }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first path for the ApplicationContext is given and this file is used a s resource by the container.  BeanFactory(or Container) uses this xml file to get the bean we defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However Setter Injection adds the abstraction for the developer to know which dependencies are needed when. But it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39813</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39813"/>
		<updated>2010-11-03T00:20:33Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 '' Employee.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 ''Department.java''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationContext.xml''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, we only need to update our configuration file. There is  no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write the loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is the technique to add the dependency for interfaces in the components at run time, and components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using Avalon framework:&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 ''ApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 ''AccountApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 ''CustomerApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface, and we have ApplicationServiceImpl class(component) implementing the ApplicationService inteface, which will do the specific implementation of the ApplicationDAO  interface provided by the container as per the configuration.&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationService.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationServiceImpl.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container which use configuration file for lookup, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
Configuration File that will be used by MyClass file to lookup the dependency configurations.&lt;br /&gt;
&lt;br /&gt;
 ''App.Config''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Here, in this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference, and which getEntity() is invoked (of Accoun ot Customer ) actually depends on the dependency that is injected via configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state (variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us take an example of Setter injection by using Spring Framework. [] Before using Spring, let us study some basic features of Springs. We are not including detailed explanation and complicacies of Springs here, for better understanding you can visit the site:  [ ]&lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[ ], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will see Setter and Constructor Injection using Spring Framework.&lt;br /&gt;
&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is a class on which DoctorService depends.&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
           { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
           }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
           { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
            }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
            {&lt;br /&gt;
              System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
              System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
             }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
        private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
                return  this.prescription;&lt;br /&gt;
        }&lt;br /&gt;
        public void setPrescription(String prescription) &lt;br /&gt;
        {&lt;br /&gt;
           this. prescription = prescription;&lt;br /&gt;
         }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above example, the invoking object is responsible for setting the PrescriptionDAO dependency. Now there is no code inside the class that is creating new instance of PrescriptionDAO, because this will be done by the Spring container by looking for dependencies of DoctorService inside applicationContext.xml file, which is usually stired in WEB-INF folder of web application&lt;br /&gt;
&lt;br /&gt;
Spring framework uses setter method to create this dependent object, and note the  &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
For Constructor injection, it uses another tag, &amp;lt;constructor-arg&amp;gt;, we will refer to it later.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
  &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
 &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions defined inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
 public class MyClient{&lt;br /&gt;
 public static void main(String args[])&lt;br /&gt;
        {&lt;br /&gt;
                Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
                BeanFactory factory =new XmlBeanFactory(res);&lt;br /&gt;
		//” doctorServiceId” is the same id defined in ApplicationContext.xml&lt;br /&gt;
        	DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
	}&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first path for the ApplicationContext is given and this file is used a s resource by the container.  BeanFactory(or Container) uses this xml file to get the bean we defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However Setter Injection adds the abstraction for the developer to know which dependencies are needed when. But it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39811</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39811"/>
		<updated>2010-11-03T00:18:00Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 '' Employee.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 ''Department.java''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationContext.xml''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, we only need to update our configuration file. There is  no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write the loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is the technique to add the dependency for interfaces in the components at run time, and components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using Avalon framework:&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 ''ApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 ''AccountApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 ''CustomerApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface, and we have ApplicationServiceImpl class(component) implementing the ApplicationService inteface, which will do the specific implementation of the ApplicationDAO  interface provided by the container as per the configuration.&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationService.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationServiceImpl.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container which use configuration file for lookup, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
Configuration File that will be used by MyClass file to lookup the dependency configurations.&lt;br /&gt;
&lt;br /&gt;
 ''App.Config''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Here, in this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference, and which getEntity() is invoked (of Accoun ot Customer ) actually depends on the dependency that is injected via configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state (variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us take an example of Setter injection by using Spring Framework. [] Before using Spring, let us study some basic features of Springs. We are not including detailed explanation and complicacies of Springs here, for better understanding you can visit the site:  [ ]&lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[ ], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will see Setter and Constructor Injection using Spring Framework.&lt;br /&gt;
&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is a class on which DoctorService depends.&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
           { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
           }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
           { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
            }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
            {&lt;br /&gt;
              System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
              System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
             }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
	private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
                return  this.prescription;&lt;br /&gt;
	}&lt;br /&gt;
        public void setPrescription(String prescription) &lt;br /&gt;
        {&lt;br /&gt;
           this. prescription = prescription;&lt;br /&gt;
         }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above example, the invoking object is responsible for setting the PrescriptionDAO dependency. Now there is no code inside the class that is creating new instance of PrescriptionDAO, because this will be done by the Spring container by looking for dependencies of DoctorService inside applicationContext.xml file, which is usually stired in WEB-INF folder of web application&lt;br /&gt;
&lt;br /&gt;
Spring framework uses setter method to create this dependent object, and note the  &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
For Constructor injection, it uses another tag, &amp;lt;constructor-arg&amp;gt;, we will refer to it later.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
  &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
 &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions defined inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
 public class MyClient{&lt;br /&gt;
 public static void main(String args[]){&lt;br /&gt;
&lt;br /&gt;
		Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
		BeanFactory factory =new XmlBeanFactory(res);&lt;br /&gt;
		//” doctorServiceId” is the same id defined in ApplicationContext.xml &lt;br /&gt;
		DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
	}&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first path for the ApplicationContext is given and this file is used a s resource by the container.  BeanFactory(or Container) uses this xml file to get the bean we defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However Setter Injection adds the abstraction for the developer to know which dependencies are needed when. But it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39807</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39807"/>
		<updated>2010-11-03T00:14:59Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 '' Employee.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 ''Department.java''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationContext.xml''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, we only need to update our configuration file. There is  no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write the loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is the technique to add the dependency for interfaces in the components at run time, and components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using Avalon framework:&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 ''ApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 ''AccountApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 ''CustomerApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface, and we have ApplicationServiceImpl class(component) implementing the ApplicationService inteface, which will do the specific implementation of the ApplicationDAO  interface provided by the container as per the configuration.&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationService.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationServiceImpl.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container which use configuration file for lookup, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
Configuration File that will be used by MyClass file to lookup the dependency configurations.&lt;br /&gt;
&lt;br /&gt;
 ''App.Config''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Here, in this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference, and which getEntity() is invoked (of Accoun ot Customer ) actually depends on the dependency that is injected via configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state (variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us take an example of Setter injection by using Spring Framework. [] Before using Spring, let us study some basic features of Springs. We are not including detailed explanation and complicacies of Springs here, for better understanding you can visit the site:  [ ]&lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[ ], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will see Setter and Constructor Injection using Spring Framework.&lt;br /&gt;
&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is a class on which DoctorService depends.&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
           { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
           }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
           { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
            }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
            {&lt;br /&gt;
	      System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
	      System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
            }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
        private String prescription;&lt;br /&gt;
	private int dose;&lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
		return  this.prescription;&lt;br /&gt;
	}&lt;br /&gt;
        public void setPrescription (String prescription) &lt;br /&gt;
        {&lt;br /&gt;
		this. prescription = prescription;&lt;br /&gt;
	}&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above example, the invoking object is responsible for setting the PrescriptionDAO dependency. Now there is no code inside the class that is creating new instance of PrescriptionDAO, because this will be done by the Spring container by looking for dependencies of DoctorService inside applicationContext.xml file, which is usually stired in WEB-INF folder of web application&lt;br /&gt;
&lt;br /&gt;
Spring framework uses setter method to create this dependent object, and note the  &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
For Constructor injection, it uses another tag, &amp;lt;constructor-arg&amp;gt;, we will refer to it later.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
 &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
  &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
 &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions defined inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
&lt;br /&gt;
 public class MyClient{&lt;br /&gt;
 public static void main(String args[]){&lt;br /&gt;
&lt;br /&gt;
		Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
		BeanFactory factory =new XmlBeanFactory(res);&lt;br /&gt;
		//” doctorServiceId” is the same id defined in ApplicationContext.xml &lt;br /&gt;
		DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
	}&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Here, first path for the ApplicationContext is given and this file is used a s resource by the container.  BeanFactory(or Container) uses this xml file to get the bean we defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However Setter Injection adds the abstraction for the developer to know which dependencies are needed when. But it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39804</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39804"/>
		<updated>2010-11-03T00:12:51Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 '' Employee.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 ''Department.java''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationContext.xml''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, we only need to update our configuration file. There is  no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write the loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is the technique to add the dependency for interfaces in the components at run time, and components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using Avalon framework:&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 ''ApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 ''AccountApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 ''CustomerApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface, and we have ApplicationServiceImpl class(component) implementing the ApplicationService inteface, which will do the specific implementation of the ApplicationDAO  interface provided by the container as per the configuration.&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationService.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationServiceImpl.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container which use configuration file for lookup, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
Configuration File that will be used by MyClass file to lookup the dependency configurations.&lt;br /&gt;
&lt;br /&gt;
 ''App.Config''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Here, in this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference, and which getEntity() is invoked (of Accoun ot Customer ) actually depends on the dependency that is injected via configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state (variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us take an example of Setter injection by using Spring Framework. [] Before using Spring, let us study some basic features of Springs. We are not including detailed explanation and complicacies of Springs here, for better understanding you can visit the site:  [ ]&lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[ ], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will see Setter and Constructor Injection using Spring Framework.&lt;br /&gt;
&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is a class on which DoctorService depends.&lt;br /&gt;
&lt;br /&gt;
 '''''DoctorService.java'''''&lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
       private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
       //empty constructor&lt;br /&gt;
       public DoctorService () {}&lt;br /&gt;
       public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
           { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
           }&lt;br /&gt;
       //setter for prescriptionDAO&lt;br /&gt;
       public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
           { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
            }&lt;br /&gt;
       //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
       public void print()&lt;br /&gt;
            {&lt;br /&gt;
	      System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
	      System.out.println(“dose: “+prescriptionDAO.dose);&lt;br /&gt;
            }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 '''''PrescriptionDAO.java'''''&lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class PrescriptionDAO&lt;br /&gt;
 {&lt;br /&gt;
&lt;br /&gt;
	private String prescription;&lt;br /&gt;
	private int dose;&lt;br /&gt;
 &lt;br /&gt;
        public PrescriptionDAO(){}&lt;br /&gt;
        public String getPrescription () &lt;br /&gt;
        {&lt;br /&gt;
		return  this.prescription;&lt;br /&gt;
	}&lt;br /&gt;
        public void setPrescription (String prescription) &lt;br /&gt;
        {&lt;br /&gt;
		this. prescription = prescription;&lt;br /&gt;
	}&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above example, the invoking object is responsible for setting the PrescriptionDAO dependency. Now there is no code inside the class that is creating new instance of PrescriptionDAO, because this will be done by the Spring container by looking for dependencies of DoctorService inside applicationContext.xml file, which is usually stired in WEB-INF folder of web application&lt;br /&gt;
&lt;br /&gt;
Spring framework uses setter method to create this dependent object, and note the  &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
For Constructor injection, it uses another tag, &amp;lt;constructor-arg&amp;gt;, we will refer to it later.&lt;br /&gt;
&lt;br /&gt;
 '''''ApplicationContext.xml'''''&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
  &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;/bean&amp;gt;&lt;br /&gt;
&lt;br /&gt;
 &amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
 &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions defined inside.&lt;br /&gt;
&lt;br /&gt;
 '''''MyClient.java'''''&lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 import java.io;&lt;br /&gt;
 import org.springframework.beans.factory.*;&lt;br /&gt;
 import org.springframework.beans.factory.xml.*;&lt;br /&gt;
 import org.springframework.core.io;&lt;br /&gt;
&lt;br /&gt;
 public class MyClient{&lt;br /&gt;
&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
&lt;br /&gt;
		Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
		BeanFactory factory =new XmlBeanFactory(res);&lt;br /&gt;
		//” doctorServiceId” is the same id defined in ApplicationContext.xml &lt;br /&gt;
		DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Here, first path for the ApplicationContext is given and this file is used a s resource by the container.  BeanFactory(or Container) uses this xml file to get the bean we defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However Setter Injection adds the abstraction for the developer to know which dependencies are needed when. But it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39803</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39803"/>
		<updated>2010-11-03T00:06:19Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 '' Employee.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 ''Department.java''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationContext.xml''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, we only need to update our configuration file. There is  no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write the loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is the technique to add the dependency for interfaces in the components at run time, and components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using Avalon framework:&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 ''ApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 ''AccountApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 ''CustomerApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface, and we have ApplicationServiceImpl class(component) implementing the ApplicationService inteface, which will do the specific implementation of the ApplicationDAO  interface provided by the container as per the configuration.&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationService.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationServiceImpl.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container which use configuration file for lookup, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
Configuration File that will be used by MyClass file to lookup the dependency configurations.&lt;br /&gt;
&lt;br /&gt;
 ''App.Config''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Here, in this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference, and which getEntity() is invoked (of Accoun ot Customer ) actually depends on the dependency that is injected via configuration file.&lt;br /&gt;
&lt;br /&gt;
==Type 2- Setter Injection==&lt;br /&gt;
&lt;br /&gt;
Dependency can be injected using the setter method of a class. If a class is dependent on another class or object instances, then the dependency should be declared as a state (variable) of the class and the class should have a setter method for it. The dependencies are set onto public attributes of the object in need. One of the primary motive for using setters, is supporting dependency injection without having to modify the constructor of a legacy class. Another use is to allow the creation of expensive resources or services as late as possible and only when needed, which is an edge over the Constructor Injection, which we will see in few moments.&lt;br /&gt;
&lt;br /&gt;
Let us take an example of Setter injection by using Spring Framework. [] Before using Spring, let us study some basic features of Springs. We are not including detailed explanation and complicacies of Springs here, for better understanding you can visit the site:  [ ]&lt;br /&gt;
&lt;br /&gt;
* Spring is a lightweight container which along with supporting features like Dependency Injection, also include other ones as:  Container, Framework, AOP[ ], MVC, etc. &lt;br /&gt;
* Spring Framework supports both Setter Injection and Constructor Injection, but not Interface Injection. Spring jars that can be included are : &lt;br /&gt;
** spring-beans.jar&lt;br /&gt;
** spring-core.jar&lt;br /&gt;
* Packages that provide Spring Frameworks’s IoC container are:&lt;br /&gt;
** org.springframeworks.beans&lt;br /&gt;
** org.springframeworks.context&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
We will see Setter and Constructor Injection using Spring Framework.&lt;br /&gt;
&lt;br /&gt;
The example below includes a class, DoctorService. The DoctorService class needs a data-access object for communicating with the database. Assume, the PrescriptionDAO (&amp;quot;order data-access object&amp;quot;) is a class on which DoctorService depends.&lt;br /&gt;
&lt;br /&gt;
 ''DoctorService.java'''''Bold text'''&lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class DoctorService&lt;br /&gt;
 {&lt;br /&gt;
	private PrescriptionDAO prescriptionDAO;&lt;br /&gt;
&lt;br /&gt;
	//empty constructor&lt;br /&gt;
 public DoctorService () {}&lt;br /&gt;
	&lt;br /&gt;
	public PrescriptionDAO getPrescriptionDAO() &lt;br /&gt;
           { &lt;br /&gt;
              return this.prescriptionDAO;&lt;br /&gt;
           }&lt;br /&gt;
&lt;br /&gt;
	//setter for prescriptionDAO&lt;br /&gt;
    	public setPrescriptionDAO(prescriptionDAO) &lt;br /&gt;
           { &lt;br /&gt;
              this.prescriptionDAO = prescriptionDAO; &lt;br /&gt;
            }&lt;br /&gt;
&lt;br /&gt;
   //business logic that actually uses prescriptionDAOto access its variables and methods.&lt;br /&gt;
   public void print()&lt;br /&gt;
       {&lt;br /&gt;
	System.out.println(“prescription: “+prescriptionDAO.prescription);&lt;br /&gt;
	System.out.println(“dose: “+prescriptionDAO.dose);	&lt;br /&gt;
       }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
PrescriptionDAO.java&lt;br /&gt;
&lt;br /&gt;
package myPackage;&lt;br /&gt;
public class PrescriptionDAO{&lt;br /&gt;
&lt;br /&gt;
	private String prescription;&lt;br /&gt;
	private int dose;&lt;br /&gt;
	&lt;br /&gt;
public PrescriptionDAO(){&lt;br /&gt;
	}&lt;br /&gt;
&lt;br /&gt;
	public String getPrescription () {&lt;br /&gt;
		return  this.prescription;&lt;br /&gt;
	}&lt;br /&gt;
 &lt;br /&gt;
	public void setPrescription (String prescription) {&lt;br /&gt;
		this. prescription = prescription;&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
In the above example, the invoking object is responsible for setting the PrescriptionDAO dependency. Now there is no code inside the class that is creating new instance of PrescriptionDAO, because this will be done by the Spring container by looking for dependencies of DoctorService inside applicationContext.xml file, which is usually stired in WEB-INF folder of web application&lt;br /&gt;
&lt;br /&gt;
Spring framework uses setter method to create this dependent object, and note the  &amp;lt;property&amp;gt; tag which is used inside ApplicationContext.xml file for setter injection. &lt;br /&gt;
For Constructor injection, it uses another tag, &amp;lt;constructor-arg&amp;gt;, we will refer to it later.&lt;br /&gt;
&lt;br /&gt;
ApplicationContext.xml&lt;br /&gt;
&lt;br /&gt;
&amp;lt;beans xmlns=&amp;quot;http://www.springframework.org/schema/beans&amp;quot;&lt;br /&gt;
    xmlns:xsi=&amp;quot;http://www.w3.org/2001/XMLSchema-instance&amp;quot;&lt;br /&gt;
    xmlns:p=&amp;quot;http://www.springframework.org/schema/p&amp;quot;&lt;br /&gt;
    xsi:schemaLocation=&amp;quot;http://www.springframework.org/schema/beans&lt;br /&gt;
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;bean id=&amp;quot;doctorServiceId &amp;quot; class=&amp;quot;myPackage.DoctorService&amp;quot;&amp;gt;&lt;br /&gt;
&lt;br /&gt;
  &amp;lt;!-- setter injection using the nested &amp;lt;ref/&amp;gt; element --&amp;gt;&lt;br /&gt;
  &amp;lt;property name=&amp;quot; prescriptionDAO &amp;quot;&amp;gt;&amp;lt;ref bean=&amp;quot; prescriptionDAOId &amp;quot;/&amp;gt;&amp;lt;/property&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/bean&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;bean id=&amp;quot; prescriptionDAOId&amp;quot;  class=&amp;quot; myPackage.PrescriptionDAO &amp;quot;&amp;gt;&lt;br /&gt;
	&amp;lt;property name=&amp;quot;prescription&amp;quot; value=&amp;quot;Take medicine regularly.&amp;quot;/&amp;gt;&lt;br /&gt;
&amp;lt;property name=&amp;quot;dose&amp;quot; value=&amp;quot;3&amp;quot;/&amp;gt;&lt;br /&gt;
&amp;lt;/bean&amp;gt;&lt;br /&gt;
&amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Now, Client is a class that is used to instantiate the Spring Container and retrieve the bean definitions defined inside.&lt;br /&gt;
&lt;br /&gt;
MyClient.java&lt;br /&gt;
&lt;br /&gt;
package myPackage;&lt;br /&gt;
import java.io;&lt;br /&gt;
import org.springframework.beans.factory.*;&lt;br /&gt;
import org.springframework.beans.factory.xml.*;&lt;br /&gt;
import org.springframework.core.io;&lt;br /&gt;
&lt;br /&gt;
public class MyClient{&lt;br /&gt;
&lt;br /&gt;
	public static void main(String args[]){&lt;br /&gt;
&lt;br /&gt;
		Resource res=new ClassPathResource(“./myPackage/ ApplicationContext.xml”);&lt;br /&gt;
		BeanFactory factory =new XmlBeanFactory(res);&lt;br /&gt;
		//” doctorServiceId” is the same id defined in ApplicationContext.xml for DoctorService class.&lt;br /&gt;
		DoctorService doctorService= (DoctorService) factory.getBean(“doctorServiceId”);&lt;br /&gt;
&lt;br /&gt;
	}&lt;br /&gt;
}&lt;br /&gt;
Here, first path for the ApplicationContext is given and this file is used a s resource by the container.  BeanFactory (or Conatiner) uses this xml file to get the bean we defined inside the configuration file.&lt;br /&gt;
&lt;br /&gt;
However Setter Injection adds the abstraction for the developer to know which dependencies are needed when. But it can save on modifying a lot of legacy code when introducing new methods, and can provide a performance boost if the dependency is expensive or not easily accessible.&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39802</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39802"/>
		<updated>2010-11-03T00:02:10Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 '' Employee.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 ''Department.java''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationContext.xml''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, we only need to update our configuration file. There is  no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write the loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is the technique to add the dependency for interfaces in the components at run time, and components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using Avalon framework:&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 ''ApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 ''AccountApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 ''CustomerApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface, and we have ApplicationServiceImpl class(component) implementing the ApplicationService inteface, which will do the specific implementation of the ApplicationDAO  interface provided by the container as per the configuration.&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationService.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationServiceImpl.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
                //code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container which use configuration file for lookup, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
            // call validateEntity()&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
Configuration File that will be used by MyClass file to lookup the dependency configurations.&lt;br /&gt;
&lt;br /&gt;
 ''App.Config''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Here, in this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference, and which getEntity() is invoked (of Accoun ot Customer ) actually depends on the dependency that is injected via configuration file.&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39801</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39801"/>
		<updated>2010-11-03T00:00:36Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 '' Employee.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 ''Department.java''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationContext.xml''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, we only need to update our configuration file. There is  no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write the loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
== Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is the technique to add the dependency for interfaces in the components at run time, and components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using Avalon framework:&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 ''ApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 ''AccountApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 ''CustomerApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface, and we have ApplicationServiceImpl class(component) implementing the ApplicationService inteface, which will do the specific implementation of the ApplicationDAO  interface provided by the container as per the configuration.&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationService.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
       getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationServiceImpl.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
        ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
                applicationDAO.getEntity();&lt;br /&gt;
		//code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container which use configuration file for lookup, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
&lt;br /&gt;
            // call validateEntity() &lt;br /&gt;
&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
Configuration File that will be used by MyClass file to lookup the dependency configurations.&lt;br /&gt;
&lt;br /&gt;
 ''App.Config''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Here, in this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference, and which getEntity() is invoked (of Accoun ot Customer ) actually depends on the dependency that is injected via configuration file.&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39800</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39800"/>
		<updated>2010-11-02T23:57:37Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 '' Employee.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 ''Department.java''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationContext.xml''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt; &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;br /&gt;
&lt;br /&gt;
Here we can see that, the classes themselves do not create their own instances, but it is the framework that does this job for them, making the code cleaner, reusable and loosely coupled. In future if one wants to add on, delete or modify any of the dependent objects, we only need to update our configuration file. There is  no need to look up the code all over again to find the class’s dependent objects. One can make modifications to the lines of code creating instances, which may be,&lt;br /&gt;
		&lt;br /&gt;
  // used everywhere in code without Dependency Injection.&lt;br /&gt;
  Department dept=new Department ();  &lt;br /&gt;
&lt;br /&gt;
Thus it makes our code configurable and maintainable. &lt;br /&gt;
Let us now move on and see some more examples to understand the different types of injections available within different frameworks.&lt;br /&gt;
&lt;br /&gt;
= Types of Dependency Injection =&lt;br /&gt;
&lt;br /&gt;
There are a number of Dependency Injection variants that exists to allow the developer to implement and write the loosely coupled code. The dependencies can be injected in various forms like: &lt;br /&gt;
* Type 1- Interface Injection&lt;br /&gt;
* Type 2- Setter Injection&lt;br /&gt;
* Type 3- Constructor Injection&lt;br /&gt;
&lt;br /&gt;
 == Type 1- Interface Injection ==&lt;br /&gt;
&lt;br /&gt;
Interface injection is the technique to add the dependency for interfaces in the components at run time, and components implement these interfaces based on the injected dependency. Spring framework does not support interface injection, so let us see this injection by using Avalon framework:&lt;br /&gt;
&lt;br /&gt;
For example, we have an ApplicationDAO interface, while AccountApplicationDAO and  CustomerApplicationDAO are the classes implementing ApplicationDAO, &lt;br /&gt;
&lt;br /&gt;
 ''ApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationDAO&lt;br /&gt;
   {&lt;br /&gt;
       void getEntity();&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 ''AccountApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class AccountApplicationDAO implements ApplicationDAO&lt;br /&gt;
     {&lt;br /&gt;
        void getEntity()&lt;br /&gt;
           {&lt;br /&gt;
             //get all accounts.&lt;br /&gt;
           }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
 ''CustomerApplicationDAO.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class CustomerApplicationDAO implements ApplicationDAO&lt;br /&gt;
      {&lt;br /&gt;
	  void getEntity()&lt;br /&gt;
             {&lt;br /&gt;
               //get all customers.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
We also have ApplicationService interface, which depends on the ApplicationDAO interface, and we have ApplicationServiceImpl class(component) implementing the ApplicationService inteface, which will do the specific implementation of the ApplicationDAO  interface provided by the container as per the configuration.&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationService.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public interface ApplicationService&lt;br /&gt;
     {&lt;br /&gt;
	 getEntity(ApplicationDAO applicationDAO);&lt;br /&gt;
     }&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationServiceImpl.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class ApplicationServiceImpl implements ApplicationService &lt;br /&gt;
     {&lt;br /&gt;
	ApplicationDAO applicationDAO;&lt;br /&gt;
        validateEntity (ApplicationDAO applicationDAO)&lt;br /&gt;
             {&lt;br /&gt;
                this. applicationDAO= applicationDAO;&lt;br /&gt;
		applicationDAO.getEntity();&lt;br /&gt;
		//code to validate the Entity (Account/Customer),as per the configuration in xml file.&lt;br /&gt;
             }&lt;br /&gt;
      }&lt;br /&gt;
&lt;br /&gt;
Now, our main program will get the interface dependency from the container which use configuration file for lookup, &lt;br /&gt;
&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class MyClass&lt;br /&gt;
 {&lt;br /&gt;
        public static void main(string[] args)&lt;br /&gt;
        {&lt;br /&gt;
            // Get the correct dependency based on configuration file&lt;br /&gt;
            ApplicationDAO dependencyDAO = getDependecny();&lt;br /&gt;
 &lt;br /&gt;
            // Create our applicationServiceImpl class and inject the dependency&lt;br /&gt;
 	    ApplicationServiceImpl applicationServiceImpl = new ApplicationServiceImpl();&lt;br /&gt;
&lt;br /&gt;
            // call validateEntity() &lt;br /&gt;
&lt;br /&gt;
            ((ApplicationService)applicationServiceImpl).validateEntity(dependencyDAO);&lt;br /&gt;
 &lt;br /&gt;
        }&lt;br /&gt;
        &lt;br /&gt;
        public static ApplicationDAO getDependency()&lt;br /&gt;
        {&lt;br /&gt;
  string implementClass =  &lt;br /&gt;
         System.Configuration.ConfigurationManager.AppSettings[&amp;quot;selectedClass&amp;quot;];&lt;br /&gt;
            Type type = System.Type.GetType(implementClass);&lt;br /&gt;
  ApplicationDAO applicationDAO = (ApplicationDAO)Activator.CreateInstance(type);&lt;br /&gt;
            return applicationDAO;&lt;br /&gt;
        }&lt;br /&gt;
 }&lt;br /&gt;
 &lt;br /&gt;
Configuration File that will be used by MyClass file to lookup the dependency configurations.&lt;br /&gt;
&lt;br /&gt;
 ''App.Config''&lt;br /&gt;
 &lt;br /&gt;
 &amp;lt;?xml version=&amp;quot;1.0&amp;quot; encoding=&amp;quot;utf-8&amp;quot; ?&amp;gt;&lt;br /&gt;
 &amp;lt;configuration&amp;gt;&lt;br /&gt;
   &amp;lt;appSettings&amp;gt;&lt;br /&gt;
     &amp;lt;add key=&amp;quot; selectedClass &amp;quot; value=&amp;quot;myPackage. AccountApplicationDAO &amp;quot; /&amp;gt;&lt;br /&gt;
   &amp;lt;/appSettings&amp;gt;&lt;br /&gt;
 &amp;lt;/configuration&amp;gt;&lt;br /&gt;
 &lt;br /&gt;
Here, in this example, validateEntity() in ApplicationServiceImpl will call getEntity() using  &lt;br /&gt;
ApplicationDAO reference, and which getEntity() is invoked (of Accoun ot Customer ) actually depends on the dependency that is injected via configuration file.&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39799</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39799"/>
		<updated>2010-11-02T23:45:25Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 '' Employee.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 ''Department.java''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationContext.xml''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as: &amp;lt;br&amp;gt;&lt;br /&gt;
[[Image:Di_image1.png]]&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39798</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39798"/>
		<updated>2010-11-02T23:44:51Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 '' Employee.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 ''Department.java''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationContext.xml''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as:&lt;br /&gt;
[[Image:Di_image1.png]]&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:Di_image1.png&amp;diff=39797</id>
		<title>File:Di image1.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:Di_image1.png&amp;diff=39797"/>
		<updated>2010-11-02T23:44:13Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: Dependency Injection image1&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;Dependency Injection image1&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39796</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39796"/>
		<updated>2010-11-02T23:35:47Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 '' Employee.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
         //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 ''Department.java''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationContext.xml''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as:&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39795</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39795"/>
		<updated>2010-11-02T23:35:13Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 '' Employee.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
	   //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
           }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 ''Department.java''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationContext.xml''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as:&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39794</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39794"/>
		<updated>2010-11-02T23:34:40Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 '' Employee.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
	   //dependent object ‘dept'&lt;br /&gt;
         private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
         setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
             this.dept=dept;&lt;br /&gt;
	   }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 ''Department.java''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
          return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationContext.xml''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as:&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39793</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39793"/>
		<updated>2010-11-02T23:32:48Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 '' Employee.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
	   //dependent object ‘dept’&lt;br /&gt;
	 private Department dept;&lt;br /&gt;
         public void Employee( )&lt;br /&gt;
           {  &lt;br /&gt;
           }&lt;br /&gt;
	 setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
		 this.dept=dept;&lt;br /&gt;
	   }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 ''Department.java''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
		return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationContext.xml''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as:&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39792</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39792"/>
		<updated>2010-11-02T23:32:07Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 '' Employee.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
	   //dependent object ‘dept’&lt;br /&gt;
	 private Department dept; &lt;br /&gt;
	 public void Employee( )&lt;br /&gt;
           {   }&lt;br /&gt;
	 setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
		 this.dept=dept;&lt;br /&gt;
	   }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 ''Department.java''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
		return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationContext.xml''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as:&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39791</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39791"/>
		<updated>2010-11-02T23:31:48Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 '' Employee.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee&lt;br /&gt;
  {&lt;br /&gt;
	 //dependent object ‘dept’&lt;br /&gt;
	 private Department dept; &lt;br /&gt;
	 public void Employee( )&lt;br /&gt;
           {   }&lt;br /&gt;
	 setDepartment(dept)&lt;br /&gt;
           {&lt;br /&gt;
		 this.dept=dept;&lt;br /&gt;
	   }&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
 ''Department.java''&lt;br /&gt;
  package myPackage;&lt;br /&gt;
  public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
		return name;&lt;br /&gt;
       }&lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationContext.xml''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as:&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39790</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39790"/>
		<updated>2010-11-02T23:29:41Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 '' Employee.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee{&lt;br /&gt;
	 //dependent object ‘dept’&lt;br /&gt;
	 private Department dept; &lt;br /&gt;
	 public void Employee( ){&lt;br /&gt;
            }&lt;br /&gt;
	 setDepartment(dept){&lt;br /&gt;
		 this.dept=dept;&lt;br /&gt;
	}&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 ''Department.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Department&lt;br /&gt;
   {&lt;br /&gt;
      private String name; &lt;br /&gt;
      public String getName()&lt;br /&gt;
       {&lt;br /&gt;
		return name;&lt;br /&gt;
       }&lt;br /&gt;
        &lt;br /&gt;
      public void setName(String name)&lt;br /&gt;
       {&lt;br /&gt;
          this.name=name;&lt;br /&gt;
       }&lt;br /&gt;
    }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationContext.xml''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as:&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39789</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39789"/>
		<updated>2010-11-02T23:27:27Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* '''Spring Framework''' – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection.&lt;br /&gt;
* '''XWork''' -  It is a standalone framework and mostly works in conjunction with Webworks. It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* '''PicoContainer''' - It is highly focused DI framework available.&lt;br /&gt;
* '''Hivelogic''' – Another DI framework to inject dependencies.&lt;br /&gt;
&lt;br /&gt;
== Example of Dependency Injection Framework ==&lt;br /&gt;
&lt;br /&gt;
Let us take a simple example to understand the basic idea of DI.&lt;br /&gt;
Suppose we have an Employee class which depends on the Department object, and we need some Assembler (DI Framework) to instantiate the Department field of Employee class, rather than Employee creates this object for itself. It will delegate this process of instantiation to any of the framework selected to do this job by using any form of configuration files, which are mostly .xml files. We will see comprehensive example using the framework in the next section. &lt;br /&gt;
&lt;br /&gt;
 '' Employee.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Employee{&lt;br /&gt;
	//dependent object ‘dept’&lt;br /&gt;
	private Department dept; &lt;br /&gt;
	public void Employee( ){&lt;br /&gt;
           }&lt;br /&gt;
	setDepartment(dept){&lt;br /&gt;
		this.dept=dept;&lt;br /&gt;
	}&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
 ''Department.java''&lt;br /&gt;
 package myPackage;&lt;br /&gt;
 public class Department{&lt;br /&gt;
	private String name;&lt;br /&gt;
	public String getName(){&lt;br /&gt;
		return name;&lt;br /&gt;
  }&lt;br /&gt;
 public void setName(String name){&lt;br /&gt;
 this.name=name;&lt;br /&gt;
  }&lt;br /&gt;
 }&lt;br /&gt;
Now, it is the framework (any one of the selected frameworks mentioned above) which will instantiate the Department object by looking into the configuration file for any existing dependencies of Employee object, and thus forms Employee object with Department instance. For example, in Spring Framework, the configuration file will be ApplicationContext.xml, where this binding of beans is done as:&lt;br /&gt;
&lt;br /&gt;
 ''ApplicationContext.xml''&lt;br /&gt;
 &amp;lt;beans&amp;gt;&lt;br /&gt;
    &amp;lt;bean id=&amp;quot;employee&amp;quot; class=&amp;quot; myPackage .Employee.java&amp;quot;&amp;gt;&lt;br /&gt;
     	   &amp;lt;property name=&amp;quot;name &amp;quot; ref=&amp;quot;yetAnotherBean&amp;quot;/&amp;gt;&lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
     &amp;lt;bean id=&amp;quot;department&amp;quot; class=&amp;quot; myPackage .Department.java&amp;quot;&amp;gt;     	&lt;br /&gt;
  	&amp;lt;property name=&amp;quot;name&amp;quot; value=&amp;quot;Java&amp;quot;/&amp;gt;      &lt;br /&gt;
      &amp;lt;/bean&amp;gt;&lt;br /&gt;
 &amp;lt;/beans&amp;gt;&lt;br /&gt;
&lt;br /&gt;
thereby creating the dependency diagram as:&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39787</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39787"/>
		<updated>2010-11-02T23:20:43Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;br /&gt;
&lt;br /&gt;
= Definition =&lt;br /&gt;
The basic concept of Dependency Injection (DI) is that you do not create the objects themselves, but describe how they should be created. It is one of the more popular design paradigms known today, by which the objects define their dependencies, i.e. the objects or classes they work with. DI pattern provides better a software design that makes the code cleaner, since the object doesn’t need to look for other components it works with, or know their location and class. http://www.springframework.net/doc-latest/reference/html/objects.html#objects-factory-collaborators&lt;br /&gt;
It facilitates the design of applications, using a framework that links the components, instead of the components linking themselves.  &lt;br /&gt;
&lt;br /&gt;
In other words, Dependency Injection, also known as Inversion Of Control (IoC), transfers the responsibility to locate and create the objects to the framework or the container which supports plug-n-play implementation, by injecting the dependencies into your code.&lt;br /&gt;
&lt;br /&gt;
Features of Dependency Injection&lt;br /&gt;
Main features of Dependency Injection Framework are:&lt;br /&gt;
* Better Design Pattern - Supports good Object-Oriented Design.&lt;br /&gt;
* Clean Code- Eliminates the need of looking up code from the application.&lt;br /&gt;
* Reuse - Promotes better code reusability.&lt;br /&gt;
* Loose Coupling- Objects are loosely coupled using DI&lt;br /&gt;
* Simple- It is very simple to implement, just need to inject the dependencies of any object.&lt;br /&gt;
* Maintainable- It is very easy to reconfigure and maintain in case of any future changes.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Dependency Injection Frameworks =&lt;br /&gt;
Dependency Injection requires a framework that helps the developer to declare the dependencies, to locate, instantiate, and initialize the components or the objects. A developer has many available frameworks to him:&lt;br /&gt;
* Spring Framework – A light weight container, most widely used for DI and very large framework, which includes a lot many other features like Aspect Oriented, framework, container, etc. along with Dependency Injection&lt;br /&gt;
* XWork -  It is a standalone framework and mostly works in conjunction with Webworks . It is highly effective command pattern framework that provides a lot of features for DI.&lt;br /&gt;
* Apache Avalon- This is also a container framework which supports the dependency injection design pattern. This frameworks is now divided into sub-frameworks.&lt;br /&gt;
* PicoContainer - It is highly focused DI framework available.&lt;br /&gt;
* Hivelogic – Another DI framework to inject dependencies.&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39786</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39786"/>
		<updated>2010-11-02T23:13:00Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Overview =&lt;br /&gt;
&lt;br /&gt;
Every enterprise application involves handful number of objects that work together to achieve some purpose. These objects are coupled with each other and work in collaboration, making the classes highly dependent. However, creating such code involving highly coupled classes defeats an important tenet of Object oriented design- ‘loose coupling’. Loose coupling means that objects should have the minimum number of dependencies, which makes the code easy to understand, modify and debug. It also allows for greater code reusability and improves the maintainability. http://www.codeproject.com/KB/architecture/DependencyInjection.aspx This drive to decouple the code from its highly dependent objects leads to the concept of Dependency Injection.&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39785</id>
		<title>CSC/ECE 517 Fall 2010/ch5 5e dr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch5_5e_dr&amp;diff=39785"/>
		<updated>2010-11-02T23:11:34Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&amp;lt;p style=&amp;quot;font-size: 24px&amp;quot;&amp;gt;'''Dependency Injection'''&amp;lt;/p&amp;gt;&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch2_S24_rm&amp;diff=36370</id>
		<title>CSC/ECE 517 Fall 2010/ch2 S24 rm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch2_S24_rm&amp;diff=36370"/>
		<updated>2010-10-01T00:12:07Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: /* C++ Template Metaprogramming */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Metaprogramming in Statically Typed Languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;I'd rather write programs that write programs than write programs&amp;quot; - Richard Sites''&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Metaprogramming is an inherent feature of dynamically typed languages [e.g. Ruby]. However, achieving metaprogramming in statically typed languages [e.g. Java] becomes complex due to compile time abstraction verification. In this topic, we explore how tools and packages are usedto implement metaprogramming in statically typed languages .&lt;br /&gt;
&lt;br /&gt;
== Metaprogramming ==&lt;br /&gt;
&lt;br /&gt;
Metaprogramming is a programming technique of writing computer programs that write or manipulate other programs or themselves, as data. [http://en.wikipedia.org/wiki/Metaprogramming] In other words, it is a programming technique of writing programs with a higher level of abstraction to make it appear as generative programming.  &lt;br /&gt;
&lt;br /&gt;
Metaprogramming involves two kinds of languages-&lt;br /&gt;
* '''Meta-language''' is the language in which meta-programs, which construct or manipulate other programs, are written. &lt;br /&gt;
* '''Object-language''' is the language of programs being manipulated. &lt;br /&gt;
This makes them ‘meta level programs’ whose problem domain are other ‘base level programs’.&lt;br /&gt;
&lt;br /&gt;
[[Image:Meta_1.jpg]]&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own metalanguage is called reflection or reflexivity.&lt;br /&gt;
&lt;br /&gt;
Simple example of a metaprogram:&lt;br /&gt;
&amp;lt;br&amp;gt;Let us consider a totally fabricated example for our understanding at very high level. Suppose we need to write a C program that printed the following 500 lines of text with a restriction that the program could not use any kind of loop or goto instruction.&lt;br /&gt;
&lt;br /&gt;
Output expected:&lt;br /&gt;
&lt;br /&gt;
  1 Mississippi&lt;br /&gt;
  2 Mississippi&lt;br /&gt;
  3 Mississippi&lt;br /&gt;
  4 Mississippi&lt;br /&gt;
  ...&lt;br /&gt;
  499 Mississippi&lt;br /&gt;
  500 Mississippi&lt;br /&gt;
&lt;br /&gt;
In C this would be then coded as:&lt;br /&gt;
&lt;br /&gt;
  #include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
  int main(void) {&lt;br /&gt;
    printf(&amp;quot;1 Mississippi\n&amp;quot;);&lt;br /&gt;
    printf(&amp;quot;2 Mississippi\n&amp;quot;);&lt;br /&gt;
        -&lt;br /&gt;
        -&lt;br /&gt;
        -&lt;br /&gt;
    printf(&amp;quot;499 Mississippi\n&amp;quot;);&lt;br /&gt;
    printf(&amp;quot;500 Mississippi\n&amp;quot;);&lt;br /&gt;
    return 0;&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
With the power of a metaprogramming language we can write another program that writes this program automatically.&lt;br /&gt;
 &lt;br /&gt;
Ruby code:&lt;br /&gt;
&lt;br /&gt;
  File.open('mississippi.c', 'w') do |output|&lt;br /&gt;
   output.puts '#include &amp;lt;stdio.h&amp;gt;'&lt;br /&gt;
   output.puts 'int main(void) {'&lt;br /&gt;
     1.upto(500) do |i|&lt;br /&gt;
       output.puts &amp;quot;    printf(\&amp;quot;#{i} &amp;quot; +&lt;br /&gt;
       &amp;quot;Mississippi\\n\&amp;quot;);&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
   output.puts '    return 0;'&lt;br /&gt;
   output.puts '}'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
This code creates a file called mississippi.c with the expected 500+ lines of C source code.Here, mississippi.c is the generated code and ruby code is the metaprogram.&lt;br /&gt;
&lt;br /&gt;
== Applications of Metaprogramming ==&lt;br /&gt;
&lt;br /&gt;
Metaprogramming is an attractive technique needed when one needs to alter the behavior of a program at run time. Due to its generative nature, it has numerous applications in program development. It can achieve program development without rewriting boiler-plate code [http://en.wikipedia.org/wiki/Boilerplate_text] all the time, ensuring efficiency, increasing modularity and minimizing inconsistent implementation errors. Program generators and program analyzers are the two main categories of meta programs. Metaprograms can be compilers, interpreters, type checkers etc. Some commonly used applications include using a program that outputs source code to - &lt;br /&gt;
* generate sine/cosine/whatever lookup tables&lt;br /&gt;
* to extract a source-form representation of a binary file&lt;br /&gt;
* to compile your bitmaps into fast display routines&lt;br /&gt;
* to extract documentation, initialization/finalization code, description tables, as well as normal code from the same source files&lt;br /&gt;
* to have customized assembly code, generated from a perl/shell/scheme script that does arbitrary processing&lt;br /&gt;
* to propagate data defined at one point only into several cross-referencing tables and code chunks. &lt;br /&gt;
&lt;br /&gt;
Programmers can focus more on the main business logic and new features to be implemented rather than writing repetitive chunks of code (e.g. setups, stubs)[1].&lt;br /&gt;
&lt;br /&gt;
= Typing in Programming Languages =&lt;br /&gt;
&lt;br /&gt;
Earlier programming languages [e.g. Assembly] were written such that each machine level function was reflected in the program code. With advancement in programming languages a certain level of abstraction was reached wherein lower level details were abstracted with one functional unit of work and represented by fewer lines of code e.g. primitive variables are represented with higher level abstract classes. With this abstraction arose a need for checking the validity of operations that could be performed with these abstractions in place.&lt;br /&gt;
&lt;br /&gt;
Typing in programming languages is property of operations and variables in the language that ensure that certain kinds of values that are invalid are not used in operations with each other. Errors related to these are known as type errors. Type checking is the process of verifying and enforcing the constraints of types. Compile time type checking also known as static type checking. Run time type checking is known as dynamic type checking. If a language specification requires its typing rules strongly (i.e., more or less allowing only those automatic type conversions which do not lose information), one can refer to the process as strongly typed, if not, as weakly typed.[http://en.wikipedia.org/wiki/Type_system]&lt;br /&gt;
The above classification can be represented as - &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Image:Meta_2.jpg]]&lt;br /&gt;
&lt;br /&gt;
== Statically Typed Programming Languages ==&lt;br /&gt;
&lt;br /&gt;
Statically typed languages ensure that a fixed type is assigned by the programmer to every variable and parameter. Thus, every expression type can be deduced and type checked during compilation. Static languages try to fix most errors during compile time and strive to minimize failures during run time. Due to this there are many type constraints on the programmer while coding.  At run time, the program uses the classes that it has been given and in this way statically typed languages make distinctions between what happens at compile time and what happens at run time. Examples of statically typed languages are C, C++, Java, C#.&lt;br /&gt;
&lt;br /&gt;
== Dynamically Typed Programming Languages ==&lt;br /&gt;
&lt;br /&gt;
In dynamically typed languages, the variables and parameters do not have a designated type and may take different values at different times. In all the operations, the operands must be type checked at runtime just before performing the operation. Dynamically typed languages don’t need to make a distinction between classes created at compile time and classes provided.  It is possible to define classes at run time and in fact, classes are always defined at run time. These eliminate many developer constraints by avoiding the need of book keeping, declarations etc. Due to this flexibility these languages make an ideal candidate for prototyping and are widely used in agile development environments. However, dynamic languages are known to have performance issues. Static languages have code optimization features at compile time, but dynamic languages allow runtime code optimizations only. [http://www.slideshare.net/aminbandeali/dynamically-and-statically-typed-languages] In dynamically typed languages,  the interpreter deduces type and type conversions, this makes development time faster, but it also can provoke runtime failures. These runtime failures are caught early on during compile time for statically typed languages.&lt;br /&gt;
Examples of dynamically typed languages include Perl, Python,  JavaScript, PHP, Ruby, Groovy.&lt;br /&gt;
&lt;br /&gt;
= Metaprogramming in statically typed languages =&lt;br /&gt;
&lt;br /&gt;
In safety languages [syntactically verbose], metaprogramming is not a standard feature, it can however be achieved. Also, static typing in meta-programs has a number of advantages. In addition to guaranteeing that the meta-program encounters no type-errors while manipulating object-programs, a statically typed metaprogramming language can also guarantee that any of the object-programs generated by the meta-program are also type-correct. A disadvantage of these type system is that (in case of meta-programming languages with weaker type systems) they sometime may be too restrictive in object-programs that the programmer is allowed to construct.&lt;br /&gt;
&lt;br /&gt;
== Techniques and Packages ==&lt;br /&gt;
&lt;br /&gt;
Many language features can be leveraged to achieve some form of characteristics needed to achieve metaprogramming. For instance, languages that support  reflection also allow for dynamic code generation.  e.g. In Microsoft .NET Framework use of &amp;quot;System.Reflection.Emit&amp;quot; namespace is used to generate types and methods at runtime. &lt;br /&gt;
&lt;br /&gt;
=== Reflection ===&lt;br /&gt;
&lt;br /&gt;
Reflection is a valuable language feature to facilitate metaprogramming. Reflection is defined as the ability of a programming language to be its own meta-language. Thus, reflection is writing programs that manipulate other programs or themselves. [http://www.developer.com/java/web/article.php/3504271/Java-Reflection-in-Action.htm] &amp;lt;br&amp;gt;&lt;br /&gt;
e.g. In Java, reflection enables to discover information about the loaded classes:&lt;br /&gt;
* Fields,&lt;br /&gt;
* Methods and constructors&lt;br /&gt;
* Generics information&lt;br /&gt;
* Metadata annotations&lt;br /&gt;
It also enables to use these metaobjects to their instances in run time environment.&lt;br /&gt;
E.g. Method.invoke(Object o, Object… args)&lt;br /&gt;
With the Java reflection API, you can interrogate an object to get all sorts of information about its class. &lt;br /&gt;
&lt;br /&gt;
Consider the following simple example:   &lt;br /&gt;
  public class HelloWorld {&lt;br /&gt;
    public void printName() {&lt;br /&gt;
      System.out.println(this.getClass().getName());&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
The line&lt;br /&gt;
  (new HelloWorld()).printName();&lt;br /&gt;
sends the string HelloWorld to standard out. Now let x be an instance of HelloWorld or one of its subclasses. The line&lt;br /&gt;
  x.printName();&lt;br /&gt;
sends the string naming the class to standard out.&lt;br /&gt;
&lt;br /&gt;
The printName method examines the object for its class (this.getClass()). In doing so, the decision of what to print is made by delegating to the object's class. The method acts on this decision by printing the returned name. Without being overridden, the printName method behaves differently for each subclass than it does for HelloWorld. The printName method is flexible; it adapts to the class that inherits it, causing the change in behavior.&lt;br /&gt;
&lt;br /&gt;
=== Annotations ===&lt;br /&gt;
&lt;br /&gt;
Annotations are a metaprogramming facility that allow the code to be marked with defined tags. Many APIs require a fair amount of boilerplate code. This boilerplate could be generated automatically by a tool if the program were “decorated” with annotations indicating which methods were remotely accessible. Metadata provided using annotations is beneficial for documentation, compiler checking, and code analysis. One can use this metadata to indicate if methods are dependent on other methods, if they are incomplete, if a certain class must reference another class, and so on. It is used by the compiler to perform some basic compile-time checking. For example there is a override annotation that lets you specify that a method overrides another method from a superclass. At this, the Java compiler will ensure that the behavior you indicate in your metadata actually happens at a code level as well.&lt;br /&gt;
&lt;br /&gt;
An “annotation” has an “annotation type” associated with it which is used for defining it. It is used when you want to create a custom annotation. The type is the actual construct used, and the annotation is the specific usage of that type. An annotation type definition takes an &amp;quot;at&amp;quot; (@) sign, followed by the interface keyword plus the annotation name. On the other hand, an annotation takes the form of an &amp;quot;at&amp;quot; sign (@), followed by the annotation type [http://www.developer.com/java/other/article.php/3556176/An-Introduction-to-Java-Annotations.htm].&lt;br /&gt;
&lt;br /&gt;
Example to Define an Annotation (Annotation type)&lt;br /&gt;
   &lt;br /&gt;
  public @interface MyAnnotation {&lt;br /&gt;
    String doSomething();}&lt;br /&gt;
   Example to Annotate Your Code (Annotation)&lt;br /&gt;
   MyAnnotation (doSomething=&amp;quot;What to do&amp;quot;)&lt;br /&gt;
   public void mymethod() {&lt;br /&gt;
   ....&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
==== Annotation Types ====&lt;br /&gt;
There are three annotation types:&lt;br /&gt;
* '''Marker:''' Marker type annotations have no elements, except the annotation name itself.&lt;br /&gt;
Example:&lt;br /&gt;
  public @interface MyAnnotation {&lt;br /&gt;
  } &lt;br /&gt;
Usage:&lt;br /&gt;
  @MyAnnotation&lt;br /&gt;
  public void mymethod() {&lt;br /&gt;
   ....&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
* '''Single-Element:''' Single-element, or single-value type, annotations provide a single piece of data only. This can be represented with a data=value pair or, simply with the value (a shortcut syntax) only, within parenthesis.&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
  public @interface MyAnnotation&lt;br /&gt;
  {&lt;br /&gt;
    String doSomething();&lt;br /&gt;
  } &lt;br /&gt;
&lt;br /&gt;
Usage:&lt;br /&gt;
  @MyAnnotation (&amp;quot;What to do&amp;quot;)&lt;br /&gt;
  public void mymethod() {&lt;br /&gt;
   ....&lt;br /&gt;
  } &lt;br /&gt;
&lt;br /&gt;
* '''Full-value or multi-value:''' Full-value type annotations have multiple data members. Therefore, you must use a full data=value parameter syntax for each member.&lt;br /&gt;
Example:&lt;br /&gt;
  public @interface MyAnnotation {&lt;br /&gt;
    String doSomething();&lt;br /&gt;
    int count; String date();&lt;br /&gt;
  } &lt;br /&gt;
Usage:&lt;br /&gt;
  @MyAnnotation (doSomething=&amp;quot;What to do&amp;quot;, count=1,&lt;br /&gt;
              date=&amp;quot;09-09-2005&amp;quot;)&lt;br /&gt;
  public void mymethod() {&lt;br /&gt;
&lt;br /&gt;
=== Generics ===&lt;br /&gt;
&lt;br /&gt;
Generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated  when needed for specific types provided as parameters. [http://en.wikipedia.org/wiki/Generic_programming] Java Generics are primarily a way for library authors to write something once, which users can customize to their own types. They allow the creation of classes and methods that work in the same way on different types of objects. The term &amp;quot;generic&amp;quot; comes from the idea that we'd like to be able to write general algorithms that can be broadly reused for many types of objects rather than having to adapt our code to fit each circumstance.&lt;br /&gt;
&lt;br /&gt;
Generics add a way to specify concrete types to general purpose classes and methods that operated on object before. A Java collection is a flexible data structure that can hold heterogeneous objects where the elements may have any reference type. When you take an element out of a collection, you must cast it to the type of element that is stored in the collection. Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that the collection has been used consistently and can insert the correct casts on values being taken out of the collection.[5] Generics are implemented by type erasure: generic type information is present only at compile time, after which it is erased by the compiler. The main advantage of this approach is that it provides total interoperability between generic code and legacy code that uses non-parametrized types (which are technically known as raw types).&lt;br /&gt;
&lt;br /&gt;
Consider a non-generic example:&lt;br /&gt;
   //This program removes 4-letter words from c. Elements must be strings&lt;br /&gt;
   static void expurgate(Collection c)  &lt;br /&gt;
   {    &lt;br /&gt;
        for (Iterator i = c.iterator(); i.hasNext(); )      &lt;br /&gt;
        if (((String) i.next()).length() == 4)        &lt;br /&gt;
        i.remove();&lt;br /&gt;
    }&lt;br /&gt;
Here is the same example modified to use generics:&lt;br /&gt;
   //This program removes the 4-letter words from c&lt;br /&gt;
  static void expurgate(Collection&amp;lt;String&amp;gt; c) &lt;br /&gt;
  {    &lt;br /&gt;
    for (Iterator&amp;lt;String&amp;gt; i = c.iterator(); i.hasNext(); )&lt;br /&gt;
    if (i.next().length() == 4)&lt;br /&gt;
    i.remove();&lt;br /&gt;
  }&lt;br /&gt;
The declaration above reads as “Collection of String c.” Collection is a generic class that takes ‘String’ as its type parameter. The code using generics is clearer and safer. Unsafe cast and a number of extra parentheses have been eliminated. More importantly, we have moved part of the specification of the method from a comment to its signature, so the compiler can verify at compile time that the type constraints are not violated at run time.[http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf]&lt;br /&gt;
&lt;br /&gt;
=== Template Metaprogramming ===&lt;br /&gt;
Template metaprogramming(TMP) or Static Metaprogramming is a technique that allows the execution of programs at compile-time. It uses extremely early binding.&lt;br /&gt;
A primary requirement for a metaprogramming language is providing high-level abstractions to hide the internal representation of base programs.[http://lcgapp.cern.ch/project/architecture/ReflectionPaper.pdf] Each template language is specific for a base language and is generated from it. In this sense, a language of templates is a superset of the base language. Thus templates are abstractions that encapsulate a program pattern written by example.  This concept has been explained in detail in [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch2_S24_rm#C.2B.2B_Template_Metaprogramming section 3.2.5]&lt;br /&gt;
&lt;br /&gt;
Uses of template metaprogramming:&lt;br /&gt;
* Compile-time dimensional analysis&lt;br /&gt;
* Multiple dispatch&lt;br /&gt;
* Design patterns&lt;br /&gt;
* Code optimization &lt;br /&gt;
* Lexing and parsing&lt;br /&gt;
&lt;br /&gt;
== Packages ==&lt;br /&gt;
&lt;br /&gt;
=== Javassist (Java Programming Assistant) ===&lt;br /&gt;
&lt;br /&gt;
Javassist is a Java library providing means to manipulate the Java bytecode of an application. It provides the support for structural reflection, i.e. the ability to change the implementation of a class at runtime. [http://www.csg.is.titech.ac.jp/~chiba/javassist/] Javassist is explicit metaprogramming, in which the metalanguage is Java. It is a load-time reflective system for Java which enables Java programs to define a new class at runtime and to modify a class file when the JVM loads it. Unlike other similar bytecode editors, Javassist provides two levels of API: source level and bytecode level.&lt;br /&gt;
&lt;br /&gt;
If the users use the source-level API, they can edit a class file without knowledge of the specifications of the Java bytecode. They do not have to even write an inserted bytecode sequence; Javassist instead can compile a fragment of source text on line (for example, just a single statement). This ease of use is a unique feature of Javassit against other tools. One can even specify inserted bytecode in the form of source text and Javassist compiles it on the fly. On the other hand, the bytecode-level API allows the users to directly edit a class file as other editors. Thus it makes Java bytecode manipulation simple.&lt;br /&gt;
&lt;br /&gt;
Javassist has the following applications:&lt;br /&gt;
* Aspect Oriented Programming:     Javassist can be a good tool for introducing new methods into a class and for inserting before/after/around advice at the both caller and callee sides.&lt;br /&gt;
* Reflection:     One of applications of Javassist is runtime reflection; Javassist enables Java programs to use a metaobject that controls method calls on base-level objects. No specialized compiler or virtual machine are needed.&lt;br /&gt;
* Remote method invocation:     Another application is remote method invocation. Javassist enables applets to call a method on a remote object running on the web server. Unlike the Java RMI, the programmer does notneed a stub compiler such as rmic; the stub code is dynamically produced by Javassist.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
  BufferedInputStream fin = new BufferedInputStream(new FileInputStream(&amp;quot;Point.class&amp;quot;));&lt;br /&gt;
  ClassFile cf = new ClassFile(new DataInputStream(fin));&lt;br /&gt;
&lt;br /&gt;
A ClassFile object can be written back to a class file. write() in ClassFile writes the contents of the class file to a given DataOutputStream. ClassFile provides addField() and addMethod() for adding a field or a method (note that a constructor is regarded as a method at the bytecode level). It also provides addAttribute() for adding an attribute to the class file.&lt;br /&gt;
&lt;br /&gt;
To examine every bytecode instruction in a method body, CodeIterator is useful. A CodeIterator object allows you to visit every bytecode instruction one by one from the beginning to the end. To otbain this object, do as follows:&lt;br /&gt;
&lt;br /&gt;
     ClassFile cf = ... ;&lt;br /&gt;
     MethodInfo minfo = cf.getMethod(&amp;quot;move&amp;quot;);    // we assume move is not overloaded.&lt;br /&gt;
     CodeAttribute ca = minfo.getCodeAttribute();&lt;br /&gt;
     CodeIterator i = ca.iterator();&lt;br /&gt;
&lt;br /&gt;
Other extensions are being developed to include reflective systems for C++ and Java e.g. OpenC++ and OpenJava which are extensible preprocessors based on compile-time reflection in C++ and Java respectively.&lt;br /&gt;
&lt;br /&gt;
=== JRuby ===&lt;br /&gt;
&lt;br /&gt;
JRuby is a complete implementation of Ruby in Java. The scripting and functional features of the Ruby language can be used by Java developers.[http://depth-first.com/articles/2006/10/24/metaprogramming-with-ruby-mapping-java-packages-onto-ruby-modules] Simple metaprogramming techniques can be  extended from  Ruby so that Java packages are mapped onto to Ruby modules. This would be something like a Ruby-Java Bridge, since JRuby can be run from any platform with a JVM.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
Using JRuby API calling JRuby from Java&lt;br /&gt;
&lt;br /&gt;
    import org.jruby.*;&lt;br /&gt;
    public class SimpleJRubyCall {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
        Ruby runtime = Ruby.getDefaultInstance();&lt;br /&gt;
    runtime.evalScript(“puts 1+2”);&lt;br /&gt;
      }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
With metaprogramming using JRuby one can&lt;br /&gt;
* add methods to class,&lt;br /&gt;
*  add instance methods&lt;br /&gt;
*  add to have Java classes&lt;br /&gt;
&lt;br /&gt;
Since metaprogramming empowers the programmer to create domain specific languages(DSL), the ones created by JRuby can always leverage Java libraries to build wrapper functionalities.&lt;br /&gt;
e.g. Simple JRuby DSL on top of HtmlUnit&lt;br /&gt;
&lt;br /&gt;
=== AspectJ ===&lt;br /&gt;
Another library worth mentioning here is AspectJ. It enforces the aspect oriented programming (AOP) approach in Java. Aspect oriented programming is a complimentary programming paradigm to object oriented programming and is used to improve the modularity of software systems. Thus, while object oriented programming is great for modeling common behavior on a hierarchy of objects, aspect oriented programming allows you to define cross-cutting concerns by adding direct semantics and can be applied across heterogeneous object models. [http://static.springsource.org/spring/docs/2.0.x/reference/aop.html] Applications of aspect oriented programming include logging, instrumenting and debugging. &lt;br /&gt;
&lt;br /&gt;
In object oriented programs, the natural unit of modularity is the class. In AspectJ, aspects modularize concerns that affect more than one class. In addition to classes, aspect oriented programming uses 'aspects'. Aspects enable modularization of crosscutting concerns such as transaction management that cut across multiple types and objects. Thus, AspectJ package achieves metaprogramming features with more controllability.&lt;br /&gt;
&lt;br /&gt;
AspectJ introduces declaring aspects in the statically typed language Java by using 3 key concepts -&lt;br /&gt;
* Join Points - well defined points in program execution&lt;br /&gt;
* Advice - defines additional code to be executed around join points&lt;br /&gt;
* Pointcut - define those points in the source code of a program where an advice will be applied&lt;br /&gt;
&lt;br /&gt;
The core task of AspectJ's advice weaver is to statically transform a program so that at runtime it will behave according to the AspectJ language semantics. The AspectJ weaver takes class files as input and produces class files as output. The weaving process itself can take place at one of three different times: compile-time, post-compile time, and load-time. These two java files are 'woven' together by compiler i.e. the class and the aspect behavior are tied together. This is also known as 'plugging-in' the aspect. [http://oreilly.com/catalog/9780596006549]&lt;br /&gt;
&lt;br /&gt;
Example - Simple tracing/logging&lt;br /&gt;
&lt;br /&gt;
Consider the HelloWorld class below which implements an application that simply displays &amp;quot;Hello World!&amp;quot; on the standard output.&lt;br /&gt;
 package helloworld; &lt;br /&gt;
 class HelloWorld {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
            new HelloWorld().printMessage();&lt;br /&gt;
    }   &lt;br /&gt;
    void printMessage() {&lt;br /&gt;
            System.out.println(&amp;quot;Hello world!&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Consider another Java source file with an aspect definition as follows - &lt;br /&gt;
 package helloworld;&lt;br /&gt;
 aspect Trace of eachobject(instanceof(HelloWorld)) {&lt;br /&gt;
    pointcut printouts(): receptions(void printMessage());&lt;br /&gt;
    before(): printouts() {&lt;br /&gt;
              System.out.println(&amp;quot;*** Entering printMessage ***&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    after():  printouts() {&lt;br /&gt;
              System.out.println(&amp;quot;*** Exiting printMessage ***&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In above example, the Trace aspect injects tracing messages before and after method main of class HelloWorld. If one does not want tracing, one can simply leave the aspect out and plug it in as and when required.&lt;br /&gt;
&lt;br /&gt;
In contrast to reflection[low level], AspectJ provides more carefully controlled power, drawing on the rules learned from object-oriented development to encourage a clean and understandable program structure. An aspect imposes behavior on a class, rather than a class requesting behavior from an aspect. An aspect can modify a class without needing to edit that class - also known as 'reverse inheritance'.&lt;br /&gt;
&lt;br /&gt;
=== MetaJ ===&lt;br /&gt;
&lt;br /&gt;
MetaJ is another package that supports metaprogramming in the Java language. A MetaJ program consists of the Java code with special metaprogramming declarations that will control how the output code is created. It uses templates and reflection. Templates are abstractions that encapsulate a program pattern written by example. Templates are translated to Java classes, so they can be accessed in the metaprogram. Accessing patterns by example inside ordinary Java programs is a major feature of MetaJ programming. [http://www.jucs.org/jucs_10_7/metaj_an_extensible_environment] &lt;br /&gt;
&lt;br /&gt;
Language Dependency:&lt;br /&gt;
MetaJ comprises of a set of concepts that are independent of the base language. These are syntax trees, code references, code iterators and code templates. A framework is defined which in which features common to most languages are abstracted. This supports independence from base language. Thus, generic operations can be defined and components that are language dependent can be plugged onto it. &lt;br /&gt;
&lt;br /&gt;
Execution Flow Representation:&lt;br /&gt;
&lt;br /&gt;
[[Image:Meta_3.jpg]]&lt;br /&gt;
&lt;br /&gt;
Example: &lt;br /&gt;
&lt;br /&gt;
Template :  SampleTempl&lt;br /&gt;
&lt;br /&gt;
 package myTempl; &lt;br /&gt;
 language = Java // base language plug­in&lt;br /&gt;
 template #CompilationUnit SampleTempl{ &lt;br /&gt;
 #[#PackageDeclaration:pck]# &lt;br /&gt;
 #[#ImportDeclarationList:imps]# &lt;br /&gt;
 class SampleTempl { ... } &lt;br /&gt;
 #TypeDeclaration:td &lt;br /&gt;
 } &lt;br /&gt;
&lt;br /&gt;
Instance of Template : Java Code &lt;br /&gt;
&lt;br /&gt;
 package myTempl; &lt;br /&gt;
 import metaj.framework.AbstractTemplate; &lt;br /&gt;
 public class SampleTempl extends AbstractTemplate{ &lt;br /&gt;
 public final Reference imps, td, pck;&lt;br /&gt;
 ... // Implementation of superclass abstract methods&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Java SDK7 has added support for dynamic typing and metaprogramming and includes MetaJ implementation.&lt;br /&gt;
&lt;br /&gt;
=== C++ Template Metaprogramming ===&lt;br /&gt;
&lt;br /&gt;
In C++, [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch2_S24_rm#Template_Metaprogramming static metaprogramming] is implemented with the help of reflection. The most important implementation of reflection in C++ is using the feature of run time type-identification (RTTI) [http://depth-first.com/articles/2006/10/24/metaprogramming-with-ruby-mapping-java-packages-onto-ruby-modules]. RTTI is a system that keeps information about an object's data type in memory at run time. Run-time type information can apply to simple data types, such as integers and characters, or to generic objects. Enabling RTTI in C++ allows the use of dynamic_cast&amp;lt;&amp;gt; operation, the typeid operator or exceptions [http://en.wikipedia.org/wiki/Run-time_type_information].&lt;br /&gt;
&lt;br /&gt;
The template mechanism in C++ allows defining parametrized classes and functions. Templates together with other C++ features constitute a Turing-complete, compile-time sub- language of C++. A Turing-complete language is a language with at least a conditional and a looping construct. C++ can be considered to be a two-level language since a C++ program may contain both static code, which is evaluated at compile time, and dynamic code, which is executed at run time. Template meta-programs are the part of a C++ source that is executed during compilation. A meta-program can access information about types not generally available to ordinary programs [9].&lt;br /&gt;
&lt;br /&gt;
Given below is an example of how to use templates for writing a common recursive factorial program:&lt;br /&gt;
  template&amp;lt;int count&amp;gt;&lt;br /&gt;
  class FACTOR{&lt;br /&gt;
  public:&lt;br /&gt;
      enum {RESULT = count * FACTOR&amp;lt;count-1&amp;gt;::RESULT};&lt;br /&gt;
       };&lt;br /&gt;
  class FACTOR&amp;lt;1&amp;gt;{&lt;br /&gt;
  public:&lt;br /&gt;
      enum {RESULT = 1};&lt;br /&gt;
       };&lt;br /&gt;
&lt;br /&gt;
If we write this-&lt;br /&gt;
  int j = FACTOR&amp;lt;5&amp;gt;::RESULT;&lt;br /&gt;
&lt;br /&gt;
The above line will calculate the value of 5 factorial. As we instantiate FACTOR&amp;lt;5&amp;gt; the definition of this class depends on FACTOR&amp;lt;4&amp;gt;, which in turn depend on FACTOR&amp;lt;3&amp;gt; and so on. The compiler needs to create all these classes until the template specialization FACTOR&amp;lt;1&amp;gt; is reached. This means the entire recursion is done by the compiler during compile time and it uses the result as if it is a constant.&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Dynamically typed languages are best suited to provide support for metaprogramming due to their inherent nature of easily overcoming distinction between code and data e.g. Lisp provides this feature of interchangeability.  Code and data are both represented in Lisp as lists, so any list can easily be treated as either code or data.  &lt;br /&gt;
It’s simple, therefore, to manipulate code as data, and then execute it – either via EVAL or by returning it as the result of a macro expansion. [3]&lt;br /&gt;
&lt;br /&gt;
Thus, statically typed languages achieve metaprogramming using various techniques and tools to achieve the level of flexibility that dynamic languages provide immanently.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://en.wikipedia.org/wiki/Metaprogramming Metaprogramming]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Boilerplate_text Boilerplate Text]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Type_system Type System]&lt;br /&gt;
*[4]  [http://www.slideshare.net/aminbandeali/dynamically-and-statically-typed-languages Bandeali, M. 2009. ''Dynamically and Statically typed languages'']&lt;br /&gt;
*[5]  [http://www.developer.com/java/web/article.php/3504271/Java-Reflection-in-Action.htm Java Reflection in Action]&lt;br /&gt;
*[6]  [http://www.developer.com/java/other/article.php/3556176/An-Introduction-to-Java-Annotations.htm An Introduction to Java Annotations]&lt;br /&gt;
*[7]  [http://en.wikipedia.org/wiki/Generic_programming Generic Programming]&lt;br /&gt;
*[8]  [http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf Haapakorpi, M. ''Metaprogramming in Java'']&lt;br /&gt;
*[9]  [http://lcgapp.cern.ch/project/architecture/ReflectionPaper.pdf Attardi, G., Cisternino, A. ''Reflection support by means of template metaprogramming'']&lt;br /&gt;
*[10] [http://www.csg.is.titech.ac.jp/~chiba/javassist/ Javassist]&lt;br /&gt;
*[11] [http://depth-first.com/articles/2006/10/24/metaprogramming-with-ruby-mapping-java-packages-onto-ruby-modules Metaprogramming with Ruby: Mapping Java Packages Onto Ruby Modules]&lt;br /&gt;
*[12] [http://static.springsource.org/spring/docs/2.0.x/reference/aop.html Aspect Oriented Programming with Spring]&lt;br /&gt;
*[13] [http://oreilly.com/catalog/9780596006549 Miles, R. 2004 ''AspectJ Cookbook'' O'Reilly Media]&lt;br /&gt;
*[14] [http://www.jucs.org/jucs_10_7/metaj_an_extensible_environment Oliveira, A.A., Braga, T.H, Maia, M.A., Bigonha and R.S. 2004. MetaJ: An Extensible Environment for Metaprogramming in Java, ''Journal of Universal Computer Science, vol. 10, no. 7 (2004), 872-891''] &lt;br /&gt;
*[15] [http://depth-first.com/articles/2006/10/24/metaprogramming-with-ruby-mapping-java-packages-onto-ruby-modules Metaprogramming with Ruby: Mapping Java Packages Onto Ruby Modules ]&lt;br /&gt;
*[16] [http://en.wikipedia.org/wiki/Run-time_type_information Run-time Type Information]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://www.cs.tut.fi/~kk/webstuff/MetaprogrammingCpp.pdf Metaprogramming in C++]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Automatic_programming Automatic/Generative Programming]&lt;br /&gt;
*[http://www.slideshare.net/dogangoko/new-features-of-java7-se-presentation News in the upcoming Java 7]&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch2_S24_rm&amp;diff=36369</id>
		<title>CSC/ECE 517 Fall 2010/ch2 S24 rm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch2_S24_rm&amp;diff=36369"/>
		<updated>2010-10-01T00:10:57Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: /* References and Notes */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Metaprogramming in Statically Typed Languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;I'd rather write programs that write programs than write programs&amp;quot; - Richard Sites''&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Metaprogramming is an inherent feature of dynamically typed languages [e.g. Ruby]. However, achieving metaprogramming in statically typed languages [e.g. Java] becomes complex due to compile time abstraction verification. In this topic, we explore how tools and packages are usedto implement metaprogramming in statically typed languages .&lt;br /&gt;
&lt;br /&gt;
== Metaprogramming ==&lt;br /&gt;
&lt;br /&gt;
Metaprogramming is a programming technique of writing computer programs that write or manipulate other programs or themselves, as data. [http://en.wikipedia.org/wiki/Metaprogramming] In other words, it is a programming technique of writing programs with a higher level of abstraction to make it appear as generative programming.  &lt;br /&gt;
&lt;br /&gt;
Metaprogramming involves two kinds of languages-&lt;br /&gt;
* '''Meta-language''' is the language in which meta-programs, which construct or manipulate other programs, are written. &lt;br /&gt;
* '''Object-language''' is the language of programs being manipulated. &lt;br /&gt;
This makes them ‘meta level programs’ whose problem domain are other ‘base level programs’.&lt;br /&gt;
&lt;br /&gt;
[[Image:Meta_1.jpg]]&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own metalanguage is called reflection or reflexivity.&lt;br /&gt;
&lt;br /&gt;
Simple example of a metaprogram:&lt;br /&gt;
&amp;lt;br&amp;gt;Let us consider a totally fabricated example for our understanding at very high level. Suppose we need to write a C program that printed the following 500 lines of text with a restriction that the program could not use any kind of loop or goto instruction.&lt;br /&gt;
&lt;br /&gt;
Output expected:&lt;br /&gt;
&lt;br /&gt;
  1 Mississippi&lt;br /&gt;
  2 Mississippi&lt;br /&gt;
  3 Mississippi&lt;br /&gt;
  4 Mississippi&lt;br /&gt;
  ...&lt;br /&gt;
  499 Mississippi&lt;br /&gt;
  500 Mississippi&lt;br /&gt;
&lt;br /&gt;
In C this would be then coded as:&lt;br /&gt;
&lt;br /&gt;
  #include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
  int main(void) {&lt;br /&gt;
    printf(&amp;quot;1 Mississippi\n&amp;quot;);&lt;br /&gt;
    printf(&amp;quot;2 Mississippi\n&amp;quot;);&lt;br /&gt;
        -&lt;br /&gt;
        -&lt;br /&gt;
        -&lt;br /&gt;
    printf(&amp;quot;499 Mississippi\n&amp;quot;);&lt;br /&gt;
    printf(&amp;quot;500 Mississippi\n&amp;quot;);&lt;br /&gt;
    return 0;&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
With the power of a metaprogramming language we can write another program that writes this program automatically.&lt;br /&gt;
 &lt;br /&gt;
Ruby code:&lt;br /&gt;
&lt;br /&gt;
  File.open('mississippi.c', 'w') do |output|&lt;br /&gt;
   output.puts '#include &amp;lt;stdio.h&amp;gt;'&lt;br /&gt;
   output.puts 'int main(void) {'&lt;br /&gt;
     1.upto(500) do |i|&lt;br /&gt;
       output.puts &amp;quot;    printf(\&amp;quot;#{i} &amp;quot; +&lt;br /&gt;
       &amp;quot;Mississippi\\n\&amp;quot;);&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
   output.puts '    return 0;'&lt;br /&gt;
   output.puts '}'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
This code creates a file called mississippi.c with the expected 500+ lines of C source code.Here, mississippi.c is the generated code and ruby code is the metaprogram.&lt;br /&gt;
&lt;br /&gt;
== Applications of Metaprogramming ==&lt;br /&gt;
&lt;br /&gt;
Metaprogramming is an attractive technique needed when one needs to alter the behavior of a program at run time. Due to its generative nature, it has numerous applications in program development. It can achieve program development without rewriting boiler-plate code [http://en.wikipedia.org/wiki/Boilerplate_text] all the time, ensuring efficiency, increasing modularity and minimizing inconsistent implementation errors. Program generators and program analyzers are the two main categories of meta programs. Metaprograms can be compilers, interpreters, type checkers etc. Some commonly used applications include using a program that outputs source code to - &lt;br /&gt;
* generate sine/cosine/whatever lookup tables&lt;br /&gt;
* to extract a source-form representation of a binary file&lt;br /&gt;
* to compile your bitmaps into fast display routines&lt;br /&gt;
* to extract documentation, initialization/finalization code, description tables, as well as normal code from the same source files&lt;br /&gt;
* to have customized assembly code, generated from a perl/shell/scheme script that does arbitrary processing&lt;br /&gt;
* to propagate data defined at one point only into several cross-referencing tables and code chunks. &lt;br /&gt;
&lt;br /&gt;
Programmers can focus more on the main business logic and new features to be implemented rather than writing repetitive chunks of code (e.g. setups, stubs)[1].&lt;br /&gt;
&lt;br /&gt;
= Typing in Programming Languages =&lt;br /&gt;
&lt;br /&gt;
Earlier programming languages [e.g. Assembly] were written such that each machine level function was reflected in the program code. With advancement in programming languages a certain level of abstraction was reached wherein lower level details were abstracted with one functional unit of work and represented by fewer lines of code e.g. primitive variables are represented with higher level abstract classes. With this abstraction arose a need for checking the validity of operations that could be performed with these abstractions in place.&lt;br /&gt;
&lt;br /&gt;
Typing in programming languages is property of operations and variables in the language that ensure that certain kinds of values that are invalid are not used in operations with each other. Errors related to these are known as type errors. Type checking is the process of verifying and enforcing the constraints of types. Compile time type checking also known as static type checking. Run time type checking is known as dynamic type checking. If a language specification requires its typing rules strongly (i.e., more or less allowing only those automatic type conversions which do not lose information), one can refer to the process as strongly typed, if not, as weakly typed.[http://en.wikipedia.org/wiki/Type_system]&lt;br /&gt;
The above classification can be represented as - &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Image:Meta_2.jpg]]&lt;br /&gt;
&lt;br /&gt;
== Statically Typed Programming Languages ==&lt;br /&gt;
&lt;br /&gt;
Statically typed languages ensure that a fixed type is assigned by the programmer to every variable and parameter. Thus, every expression type can be deduced and type checked during compilation. Static languages try to fix most errors during compile time and strive to minimize failures during run time. Due to this there are many type constraints on the programmer while coding.  At run time, the program uses the classes that it has been given and in this way statically typed languages make distinctions between what happens at compile time and what happens at run time. Examples of statically typed languages are C, C++, Java, C#.&lt;br /&gt;
&lt;br /&gt;
== Dynamically Typed Programming Languages ==&lt;br /&gt;
&lt;br /&gt;
In dynamically typed languages, the variables and parameters do not have a designated type and may take different values at different times. In all the operations, the operands must be type checked at runtime just before performing the operation. Dynamically typed languages don’t need to make a distinction between classes created at compile time and classes provided.  It is possible to define classes at run time and in fact, classes are always defined at run time. These eliminate many developer constraints by avoiding the need of book keeping, declarations etc. Due to this flexibility these languages make an ideal candidate for prototyping and are widely used in agile development environments. However, dynamic languages are known to have performance issues. Static languages have code optimization features at compile time, but dynamic languages allow runtime code optimizations only. [http://www.slideshare.net/aminbandeali/dynamically-and-statically-typed-languages] In dynamically typed languages,  the interpreter deduces type and type conversions, this makes development time faster, but it also can provoke runtime failures. These runtime failures are caught early on during compile time for statically typed languages.&lt;br /&gt;
Examples of dynamically typed languages include Perl, Python,  JavaScript, PHP, Ruby, Groovy.&lt;br /&gt;
&lt;br /&gt;
= Metaprogramming in statically typed languages =&lt;br /&gt;
&lt;br /&gt;
In safety languages [syntactically verbose], metaprogramming is not a standard feature, it can however be achieved. Also, static typing in meta-programs has a number of advantages. In addition to guaranteeing that the meta-program encounters no type-errors while manipulating object-programs, a statically typed metaprogramming language can also guarantee that any of the object-programs generated by the meta-program are also type-correct. A disadvantage of these type system is that (in case of meta-programming languages with weaker type systems) they sometime may be too restrictive in object-programs that the programmer is allowed to construct.&lt;br /&gt;
&lt;br /&gt;
== Techniques and Packages ==&lt;br /&gt;
&lt;br /&gt;
Many language features can be leveraged to achieve some form of characteristics needed to achieve metaprogramming. For instance, languages that support  reflection also allow for dynamic code generation.  e.g. In Microsoft .NET Framework use of &amp;quot;System.Reflection.Emit&amp;quot; namespace is used to generate types and methods at runtime. &lt;br /&gt;
&lt;br /&gt;
=== Reflection ===&lt;br /&gt;
&lt;br /&gt;
Reflection is a valuable language feature to facilitate metaprogramming. Reflection is defined as the ability of a programming language to be its own meta-language. Thus, reflection is writing programs that manipulate other programs or themselves. [http://www.developer.com/java/web/article.php/3504271/Java-Reflection-in-Action.htm] &amp;lt;br&amp;gt;&lt;br /&gt;
e.g. In Java, reflection enables to discover information about the loaded classes:&lt;br /&gt;
* Fields,&lt;br /&gt;
* Methods and constructors&lt;br /&gt;
* Generics information&lt;br /&gt;
* Metadata annotations&lt;br /&gt;
It also enables to use these metaobjects to their instances in run time environment.&lt;br /&gt;
E.g. Method.invoke(Object o, Object… args)&lt;br /&gt;
With the Java reflection API, you can interrogate an object to get all sorts of information about its class. &lt;br /&gt;
&lt;br /&gt;
Consider the following simple example:   &lt;br /&gt;
  public class HelloWorld {&lt;br /&gt;
    public void printName() {&lt;br /&gt;
      System.out.println(this.getClass().getName());&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
The line&lt;br /&gt;
  (new HelloWorld()).printName();&lt;br /&gt;
sends the string HelloWorld to standard out. Now let x be an instance of HelloWorld or one of its subclasses. The line&lt;br /&gt;
  x.printName();&lt;br /&gt;
sends the string naming the class to standard out.&lt;br /&gt;
&lt;br /&gt;
The printName method examines the object for its class (this.getClass()). In doing so, the decision of what to print is made by delegating to the object's class. The method acts on this decision by printing the returned name. Without being overridden, the printName method behaves differently for each subclass than it does for HelloWorld. The printName method is flexible; it adapts to the class that inherits it, causing the change in behavior.&lt;br /&gt;
&lt;br /&gt;
=== Annotations ===&lt;br /&gt;
&lt;br /&gt;
Annotations are a metaprogramming facility that allow the code to be marked with defined tags. Many APIs require a fair amount of boilerplate code. This boilerplate could be generated automatically by a tool if the program were “decorated” with annotations indicating which methods were remotely accessible. Metadata provided using annotations is beneficial for documentation, compiler checking, and code analysis. One can use this metadata to indicate if methods are dependent on other methods, if they are incomplete, if a certain class must reference another class, and so on. It is used by the compiler to perform some basic compile-time checking. For example there is a override annotation that lets you specify that a method overrides another method from a superclass. At this, the Java compiler will ensure that the behavior you indicate in your metadata actually happens at a code level as well.&lt;br /&gt;
&lt;br /&gt;
An “annotation” has an “annotation type” associated with it which is used for defining it. It is used when you want to create a custom annotation. The type is the actual construct used, and the annotation is the specific usage of that type. An annotation type definition takes an &amp;quot;at&amp;quot; (@) sign, followed by the interface keyword plus the annotation name. On the other hand, an annotation takes the form of an &amp;quot;at&amp;quot; sign (@), followed by the annotation type [http://www.developer.com/java/other/article.php/3556176/An-Introduction-to-Java-Annotations.htm].&lt;br /&gt;
&lt;br /&gt;
Example to Define an Annotation (Annotation type)&lt;br /&gt;
   &lt;br /&gt;
  public @interface MyAnnotation {&lt;br /&gt;
    String doSomething();}&lt;br /&gt;
   Example to Annotate Your Code (Annotation)&lt;br /&gt;
   MyAnnotation (doSomething=&amp;quot;What to do&amp;quot;)&lt;br /&gt;
   public void mymethod() {&lt;br /&gt;
   ....&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
==== Annotation Types ====&lt;br /&gt;
There are three annotation types:&lt;br /&gt;
* '''Marker:''' Marker type annotations have no elements, except the annotation name itself.&lt;br /&gt;
Example:&lt;br /&gt;
  public @interface MyAnnotation {&lt;br /&gt;
  } &lt;br /&gt;
Usage:&lt;br /&gt;
  @MyAnnotation&lt;br /&gt;
  public void mymethod() {&lt;br /&gt;
   ....&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
* '''Single-Element:''' Single-element, or single-value type, annotations provide a single piece of data only. This can be represented with a data=value pair or, simply with the value (a shortcut syntax) only, within parenthesis.&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
  public @interface MyAnnotation&lt;br /&gt;
  {&lt;br /&gt;
    String doSomething();&lt;br /&gt;
  } &lt;br /&gt;
&lt;br /&gt;
Usage:&lt;br /&gt;
  @MyAnnotation (&amp;quot;What to do&amp;quot;)&lt;br /&gt;
  public void mymethod() {&lt;br /&gt;
   ....&lt;br /&gt;
  } &lt;br /&gt;
&lt;br /&gt;
* '''Full-value or multi-value:''' Full-value type annotations have multiple data members. Therefore, you must use a full data=value parameter syntax for each member.&lt;br /&gt;
Example:&lt;br /&gt;
  public @interface MyAnnotation {&lt;br /&gt;
    String doSomething();&lt;br /&gt;
    int count; String date();&lt;br /&gt;
  } &lt;br /&gt;
Usage:&lt;br /&gt;
  @MyAnnotation (doSomething=&amp;quot;What to do&amp;quot;, count=1,&lt;br /&gt;
              date=&amp;quot;09-09-2005&amp;quot;)&lt;br /&gt;
  public void mymethod() {&lt;br /&gt;
&lt;br /&gt;
=== Generics ===&lt;br /&gt;
&lt;br /&gt;
Generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated  when needed for specific types provided as parameters. [http://en.wikipedia.org/wiki/Generic_programming] Java Generics are primarily a way for library authors to write something once, which users can customize to their own types. They allow the creation of classes and methods that work in the same way on different types of objects. The term &amp;quot;generic&amp;quot; comes from the idea that we'd like to be able to write general algorithms that can be broadly reused for many types of objects rather than having to adapt our code to fit each circumstance.&lt;br /&gt;
&lt;br /&gt;
Generics add a way to specify concrete types to general purpose classes and methods that operated on object before. A Java collection is a flexible data structure that can hold heterogeneous objects where the elements may have any reference type. When you take an element out of a collection, you must cast it to the type of element that is stored in the collection. Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that the collection has been used consistently and can insert the correct casts on values being taken out of the collection.[5] Generics are implemented by type erasure: generic type information is present only at compile time, after which it is erased by the compiler. The main advantage of this approach is that it provides total interoperability between generic code and legacy code that uses non-parametrized types (which are technically known as raw types).&lt;br /&gt;
&lt;br /&gt;
Consider a non-generic example:&lt;br /&gt;
   //This program removes 4-letter words from c. Elements must be strings&lt;br /&gt;
   static void expurgate(Collection c)  &lt;br /&gt;
   {    &lt;br /&gt;
        for (Iterator i = c.iterator(); i.hasNext(); )      &lt;br /&gt;
        if (((String) i.next()).length() == 4)        &lt;br /&gt;
        i.remove();&lt;br /&gt;
    }&lt;br /&gt;
Here is the same example modified to use generics:&lt;br /&gt;
   //This program removes the 4-letter words from c&lt;br /&gt;
  static void expurgate(Collection&amp;lt;String&amp;gt; c) &lt;br /&gt;
  {    &lt;br /&gt;
    for (Iterator&amp;lt;String&amp;gt; i = c.iterator(); i.hasNext(); )&lt;br /&gt;
    if (i.next().length() == 4)&lt;br /&gt;
    i.remove();&lt;br /&gt;
  }&lt;br /&gt;
The declaration above reads as “Collection of String c.” Collection is a generic class that takes ‘String’ as its type parameter. The code using generics is clearer and safer. Unsafe cast and a number of extra parentheses have been eliminated. More importantly, we have moved part of the specification of the method from a comment to its signature, so the compiler can verify at compile time that the type constraints are not violated at run time.[http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf]&lt;br /&gt;
&lt;br /&gt;
=== Template Metaprogramming ===&lt;br /&gt;
Template metaprogramming(TMP) or Static Metaprogramming is a technique that allows the execution of programs at compile-time. It uses extremely early binding.&lt;br /&gt;
A primary requirement for a metaprogramming language is providing high-level abstractions to hide the internal representation of base programs.[http://lcgapp.cern.ch/project/architecture/ReflectionPaper.pdf] Each template language is specific for a base language and is generated from it. In this sense, a language of templates is a superset of the base language. Thus templates are abstractions that encapsulate a program pattern written by example.  This concept has been explained in detail in [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch2_S24_rm#C.2B.2B_Template_Metaprogramming section 3.2.5]&lt;br /&gt;
&lt;br /&gt;
Uses of template metaprogramming:&lt;br /&gt;
* Compile-time dimensional analysis&lt;br /&gt;
* Multiple dispatch&lt;br /&gt;
* Design patterns&lt;br /&gt;
* Code optimization &lt;br /&gt;
* Lexing and parsing&lt;br /&gt;
&lt;br /&gt;
== Packages ==&lt;br /&gt;
&lt;br /&gt;
=== Javassist (Java Programming Assistant) ===&lt;br /&gt;
&lt;br /&gt;
Javassist is a Java library providing means to manipulate the Java bytecode of an application. It provides the support for structural reflection, i.e. the ability to change the implementation of a class at runtime. [http://www.csg.is.titech.ac.jp/~chiba/javassist/] Javassist is explicit metaprogramming, in which the metalanguage is Java. It is a load-time reflective system for Java which enables Java programs to define a new class at runtime and to modify a class file when the JVM loads it. Unlike other similar bytecode editors, Javassist provides two levels of API: source level and bytecode level.&lt;br /&gt;
&lt;br /&gt;
If the users use the source-level API, they can edit a class file without knowledge of the specifications of the Java bytecode. They do not have to even write an inserted bytecode sequence; Javassist instead can compile a fragment of source text on line (for example, just a single statement). This ease of use is a unique feature of Javassit against other tools. One can even specify inserted bytecode in the form of source text and Javassist compiles it on the fly. On the other hand, the bytecode-level API allows the users to directly edit a class file as other editors. Thus it makes Java bytecode manipulation simple.&lt;br /&gt;
&lt;br /&gt;
Javassist has the following applications:&lt;br /&gt;
* Aspect Oriented Programming:     Javassist can be a good tool for introducing new methods into a class and for inserting before/after/around advice at the both caller and callee sides.&lt;br /&gt;
* Reflection:     One of applications of Javassist is runtime reflection; Javassist enables Java programs to use a metaobject that controls method calls on base-level objects. No specialized compiler or virtual machine are needed.&lt;br /&gt;
* Remote method invocation:     Another application is remote method invocation. Javassist enables applets to call a method on a remote object running on the web server. Unlike the Java RMI, the programmer does notneed a stub compiler such as rmic; the stub code is dynamically produced by Javassist.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
  BufferedInputStream fin = new BufferedInputStream(new FileInputStream(&amp;quot;Point.class&amp;quot;));&lt;br /&gt;
  ClassFile cf = new ClassFile(new DataInputStream(fin));&lt;br /&gt;
&lt;br /&gt;
A ClassFile object can be written back to a class file. write() in ClassFile writes the contents of the class file to a given DataOutputStream. ClassFile provides addField() and addMethod() for adding a field or a method (note that a constructor is regarded as a method at the bytecode level). It also provides addAttribute() for adding an attribute to the class file.&lt;br /&gt;
&lt;br /&gt;
To examine every bytecode instruction in a method body, CodeIterator is useful. A CodeIterator object allows you to visit every bytecode instruction one by one from the beginning to the end. To otbain this object, do as follows:&lt;br /&gt;
&lt;br /&gt;
     ClassFile cf = ... ;&lt;br /&gt;
     MethodInfo minfo = cf.getMethod(&amp;quot;move&amp;quot;);    // we assume move is not overloaded.&lt;br /&gt;
     CodeAttribute ca = minfo.getCodeAttribute();&lt;br /&gt;
     CodeIterator i = ca.iterator();&lt;br /&gt;
&lt;br /&gt;
Other extensions are being developed to include reflective systems for C++ and Java e.g. OpenC++ and OpenJava which are extensible preprocessors based on compile-time reflection in C++ and Java respectively.&lt;br /&gt;
&lt;br /&gt;
=== JRuby ===&lt;br /&gt;
&lt;br /&gt;
JRuby is a complete implementation of Ruby in Java. The scripting and functional features of the Ruby language can be used by Java developers.[http://depth-first.com/articles/2006/10/24/metaprogramming-with-ruby-mapping-java-packages-onto-ruby-modules] Simple metaprogramming techniques can be  extended from  Ruby so that Java packages are mapped onto to Ruby modules. This would be something like a Ruby-Java Bridge, since JRuby can be run from any platform with a JVM.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
Using JRuby API calling JRuby from Java&lt;br /&gt;
&lt;br /&gt;
    import org.jruby.*;&lt;br /&gt;
    public class SimpleJRubyCall {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
        Ruby runtime = Ruby.getDefaultInstance();&lt;br /&gt;
    runtime.evalScript(“puts 1+2”);&lt;br /&gt;
      }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
With metaprogramming using JRuby one can&lt;br /&gt;
* add methods to class,&lt;br /&gt;
*  add instance methods&lt;br /&gt;
*  add to have Java classes&lt;br /&gt;
&lt;br /&gt;
Since metaprogramming empowers the programmer to create domain specific languages(DSL), the ones created by JRuby can always leverage Java libraries to build wrapper functionalities.&lt;br /&gt;
e.g. Simple JRuby DSL on top of HtmlUnit&lt;br /&gt;
&lt;br /&gt;
=== AspectJ ===&lt;br /&gt;
Another library worth mentioning here is AspectJ. It enforces the aspect oriented programming (AOP) approach in Java. Aspect oriented programming is a complimentary programming paradigm to object oriented programming and is used to improve the modularity of software systems. Thus, while object oriented programming is great for modeling common behavior on a hierarchy of objects, aspect oriented programming allows you to define cross-cutting concerns by adding direct semantics and can be applied across heterogeneous object models. [http://static.springsource.org/spring/docs/2.0.x/reference/aop.html] Applications of aspect oriented programming include logging, instrumenting and debugging. &lt;br /&gt;
&lt;br /&gt;
In object oriented programs, the natural unit of modularity is the class. In AspectJ, aspects modularize concerns that affect more than one class. In addition to classes, aspect oriented programming uses 'aspects'. Aspects enable modularization of crosscutting concerns such as transaction management that cut across multiple types and objects. Thus, AspectJ package achieves metaprogramming features with more controllability.&lt;br /&gt;
&lt;br /&gt;
AspectJ introduces declaring aspects in the statically typed language Java by using 3 key concepts -&lt;br /&gt;
* Join Points - well defined points in program execution&lt;br /&gt;
* Advice - defines additional code to be executed around join points&lt;br /&gt;
* Pointcut - define those points in the source code of a program where an advice will be applied&lt;br /&gt;
&lt;br /&gt;
The core task of AspectJ's advice weaver is to statically transform a program so that at runtime it will behave according to the AspectJ language semantics. The AspectJ weaver takes class files as input and produces class files as output. The weaving process itself can take place at one of three different times: compile-time, post-compile time, and load-time. These two java files are 'woven' together by compiler i.e. the class and the aspect behavior are tied together. This is also known as 'plugging-in' the aspect. [http://oreilly.com/catalog/9780596006549]&lt;br /&gt;
&lt;br /&gt;
Example - Simple tracing/logging&lt;br /&gt;
&lt;br /&gt;
Consider the HelloWorld class below which implements an application that simply displays &amp;quot;Hello World!&amp;quot; on the standard output.&lt;br /&gt;
 package helloworld; &lt;br /&gt;
 class HelloWorld {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
            new HelloWorld().printMessage();&lt;br /&gt;
    }   &lt;br /&gt;
    void printMessage() {&lt;br /&gt;
            System.out.println(&amp;quot;Hello world!&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Consider another Java source file with an aspect definition as follows - &lt;br /&gt;
 package helloworld;&lt;br /&gt;
 aspect Trace of eachobject(instanceof(HelloWorld)) {&lt;br /&gt;
    pointcut printouts(): receptions(void printMessage());&lt;br /&gt;
    before(): printouts() {&lt;br /&gt;
              System.out.println(&amp;quot;*** Entering printMessage ***&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    after():  printouts() {&lt;br /&gt;
              System.out.println(&amp;quot;*** Exiting printMessage ***&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In above example, the Trace aspect injects tracing messages before and after method main of class HelloWorld. If one does not want tracing, one can simply leave the aspect out and plug it in as and when required.&lt;br /&gt;
&lt;br /&gt;
In contrast to reflection[low level], AspectJ provides more carefully controlled power, drawing on the rules learned from object-oriented development to encourage a clean and understandable program structure. An aspect imposes behavior on a class, rather than a class requesting behavior from an aspect. An aspect can modify a class without needing to edit that class - also known as 'reverse inheritance'.&lt;br /&gt;
&lt;br /&gt;
=== MetaJ ===&lt;br /&gt;
&lt;br /&gt;
MetaJ is another package that supports metaprogramming in the Java language. A MetaJ program consists of the Java code with special metaprogramming declarations that will control how the output code is created. It uses templates and reflection. Templates are abstractions that encapsulate a program pattern written by example. Templates are translated to Java classes, so they can be accessed in the metaprogram. Accessing patterns by example inside ordinary Java programs is a major feature of MetaJ programming. [http://www.jucs.org/jucs_10_7/metaj_an_extensible_environment] &lt;br /&gt;
&lt;br /&gt;
Language Dependency:&lt;br /&gt;
MetaJ comprises of a set of concepts that are independent of the base language. These are syntax trees, code references, code iterators and code templates. A framework is defined which in which features common to most languages are abstracted. This supports independence from base language. Thus, generic operations can be defined and components that are language dependent can be plugged onto it. &lt;br /&gt;
&lt;br /&gt;
Execution Flow Representation:&lt;br /&gt;
&lt;br /&gt;
[[Image:Meta_3.jpg]]&lt;br /&gt;
&lt;br /&gt;
Example: &lt;br /&gt;
&lt;br /&gt;
Template :  SampleTempl&lt;br /&gt;
&lt;br /&gt;
 package myTempl; &lt;br /&gt;
 language = Java // base language plug­in&lt;br /&gt;
 template #CompilationUnit SampleTempl{ &lt;br /&gt;
 #[#PackageDeclaration:pck]# &lt;br /&gt;
 #[#ImportDeclarationList:imps]# &lt;br /&gt;
 class SampleTempl { ... } &lt;br /&gt;
 #TypeDeclaration:td &lt;br /&gt;
 } &lt;br /&gt;
&lt;br /&gt;
Instance of Template : Java Code &lt;br /&gt;
&lt;br /&gt;
 package myTempl; &lt;br /&gt;
 import metaj.framework.AbstractTemplate; &lt;br /&gt;
 public class SampleTempl extends AbstractTemplate{ &lt;br /&gt;
 public final Reference imps, td, pck;&lt;br /&gt;
 ... // Implementation of superclass abstract methods&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Java SDK7 has added support for dynamic typing and metaprogramming and includes MetaJ implementation.&lt;br /&gt;
&lt;br /&gt;
=== C++ Template Metaprogramming ===&lt;br /&gt;
&lt;br /&gt;
In C++, [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch2_S24_rm#Template_Metaprogramming static metaprogramming] is implemented with the help of reflection. The most important implementation of reflection in C++ is using the feature of run time type-identification (RTTI) [http://depth-first.com/articles/2006/10/24/metaprogramming-with-ruby-mapping-java-packages-onto-ruby-modules]. RTTI is a system that keeps information about an object's data type in memory at run time. Run-time type information can apply to simple data types, such as integers and characters, or to generic objects. Enabling RTTI in C++ allows the use of dynamic_cast&amp;lt;&amp;gt; operation, the typeid operator or exceptions [http://en.wikipedia.org/wiki/Run-time_type_information].&lt;br /&gt;
&lt;br /&gt;
The template mechanism in C++ allows defining parametrized classes and functions. Templates together with other C++ features constitute a Turing-complete, compile-time sub- language of C++. A Turing-complete language is a language with at least a conditional and a looping construct. C++ can be considered to be a two-level language since a C++ program may contain both static code, which is evaluated at compile time, and dynamic code, which is executed at run time. Template meta-programs are the part of a C++ source that is executed during compilation. A meta-program can access information about types not generally available to ordinary programs [http://lcgapp.cern.ch/project/architecture/ReflectionPaper.pdf].&lt;br /&gt;
&lt;br /&gt;
Given below is an example of how to use templates for writing a common recursive factorial program:&lt;br /&gt;
  template&amp;lt;int count&amp;gt;&lt;br /&gt;
  class FACTOR{&lt;br /&gt;
  public:&lt;br /&gt;
      enum {RESULT = count * FACTOR&amp;lt;count-1&amp;gt;::RESULT};&lt;br /&gt;
       };&lt;br /&gt;
  class FACTOR&amp;lt;1&amp;gt;{&lt;br /&gt;
  public:&lt;br /&gt;
      enum {RESULT = 1};&lt;br /&gt;
       };&lt;br /&gt;
&lt;br /&gt;
If we write this-&lt;br /&gt;
  int j = FACTOR&amp;lt;5&amp;gt;::RESULT;&lt;br /&gt;
&lt;br /&gt;
The above line will calculate the value of 5 factorial. As we instantiate FACTOR&amp;lt;5&amp;gt; the definition of this class depends on FACTOR&amp;lt;4&amp;gt;, which in turn depend on FACTOR&amp;lt;3&amp;gt; and so on. The compiler needs to create all these classes until the template specialization FACTOR&amp;lt;1&amp;gt; is reached. This means the entire recursion is done by the compiler during compile time and it uses the result as if it is a constant.&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Dynamically typed languages are best suited to provide support for metaprogramming due to their inherent nature of easily overcoming distinction between code and data e.g. Lisp provides this feature of interchangeability.  Code and data are both represented in Lisp as lists, so any list can easily be treated as either code or data.  &lt;br /&gt;
It’s simple, therefore, to manipulate code as data, and then execute it – either via EVAL or by returning it as the result of a macro expansion. [3]&lt;br /&gt;
&lt;br /&gt;
Thus, statically typed languages achieve metaprogramming using various techniques and tools to achieve the level of flexibility that dynamic languages provide immanently.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://en.wikipedia.org/wiki/Metaprogramming Metaprogramming]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Boilerplate_text Boilerplate Text]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Type_system Type System]&lt;br /&gt;
*[4]  [http://www.slideshare.net/aminbandeali/dynamically-and-statically-typed-languages Bandeali, M. 2009. ''Dynamically and Statically typed languages'']&lt;br /&gt;
*[5]  [http://www.developer.com/java/web/article.php/3504271/Java-Reflection-in-Action.htm Java Reflection in Action]&lt;br /&gt;
*[6]  [http://www.developer.com/java/other/article.php/3556176/An-Introduction-to-Java-Annotations.htm An Introduction to Java Annotations]&lt;br /&gt;
*[7]  [http://en.wikipedia.org/wiki/Generic_programming Generic Programming]&lt;br /&gt;
*[8]  [http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf Haapakorpi, M. ''Metaprogramming in Java'']&lt;br /&gt;
*[9]  [http://lcgapp.cern.ch/project/architecture/ReflectionPaper.pdf Attardi, G., Cisternino, A. ''Reflection support by means of template metaprogramming'']&lt;br /&gt;
*[10] [http://www.csg.is.titech.ac.jp/~chiba/javassist/ Javassist]&lt;br /&gt;
*[11] [http://depth-first.com/articles/2006/10/24/metaprogramming-with-ruby-mapping-java-packages-onto-ruby-modules Metaprogramming with Ruby: Mapping Java Packages Onto Ruby Modules]&lt;br /&gt;
*[12] [http://static.springsource.org/spring/docs/2.0.x/reference/aop.html Aspect Oriented Programming with Spring]&lt;br /&gt;
*[13] [http://oreilly.com/catalog/9780596006549 Miles, R. 2004 ''AspectJ Cookbook'' O'Reilly Media]&lt;br /&gt;
*[14] [http://www.jucs.org/jucs_10_7/metaj_an_extensible_environment Oliveira, A.A., Braga, T.H, Maia, M.A., Bigonha and R.S. 2004. MetaJ: An Extensible Environment for Metaprogramming in Java, ''Journal of Universal Computer Science, vol. 10, no. 7 (2004), 872-891''] &lt;br /&gt;
*[15] [http://depth-first.com/articles/2006/10/24/metaprogramming-with-ruby-mapping-java-packages-onto-ruby-modules Metaprogramming with Ruby: Mapping Java Packages Onto Ruby Modules ]&lt;br /&gt;
*[16] [http://en.wikipedia.org/wiki/Run-time_type_information Run-time Type Information]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://www.cs.tut.fi/~kk/webstuff/MetaprogrammingCpp.pdf Metaprogramming in C++]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Automatic_programming Automatic/Generative Programming]&lt;br /&gt;
*[http://www.slideshare.net/dogangoko/new-features-of-java7-se-presentation News in the upcoming Java 7]&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch2_S24_rm&amp;diff=36368</id>
		<title>CSC/ECE 517 Fall 2010/ch2 S24 rm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch2_S24_rm&amp;diff=36368"/>
		<updated>2010-10-01T00:08:29Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: /* References and Notes */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Metaprogramming in Statically Typed Languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;I'd rather write programs that write programs than write programs&amp;quot; - Richard Sites''&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Metaprogramming is an inherent feature of dynamically typed languages [e.g. Ruby]. However, achieving metaprogramming in statically typed languages [e.g. Java] becomes complex due to compile time abstraction verification. In this topic, we explore how tools and packages are usedto implement metaprogramming in statically typed languages .&lt;br /&gt;
&lt;br /&gt;
== Metaprogramming ==&lt;br /&gt;
&lt;br /&gt;
Metaprogramming is a programming technique of writing computer programs that write or manipulate other programs or themselves, as data. [http://en.wikipedia.org/wiki/Metaprogramming] In other words, it is a programming technique of writing programs with a higher level of abstraction to make it appear as generative programming.  &lt;br /&gt;
&lt;br /&gt;
Metaprogramming involves two kinds of languages-&lt;br /&gt;
* '''Meta-language''' is the language in which meta-programs, which construct or manipulate other programs, are written. &lt;br /&gt;
* '''Object-language''' is the language of programs being manipulated. &lt;br /&gt;
This makes them ‘meta level programs’ whose problem domain are other ‘base level programs’.&lt;br /&gt;
&lt;br /&gt;
[[Image:Meta_1.jpg]]&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own metalanguage is called reflection or reflexivity.&lt;br /&gt;
&lt;br /&gt;
Simple example of a metaprogram:&lt;br /&gt;
&amp;lt;br&amp;gt;Let us consider a totally fabricated example for our understanding at very high level. Suppose we need to write a C program that printed the following 500 lines of text with a restriction that the program could not use any kind of loop or goto instruction.&lt;br /&gt;
&lt;br /&gt;
Output expected:&lt;br /&gt;
&lt;br /&gt;
  1 Mississippi&lt;br /&gt;
  2 Mississippi&lt;br /&gt;
  3 Mississippi&lt;br /&gt;
  4 Mississippi&lt;br /&gt;
  ...&lt;br /&gt;
  499 Mississippi&lt;br /&gt;
  500 Mississippi&lt;br /&gt;
&lt;br /&gt;
In C this would be then coded as:&lt;br /&gt;
&lt;br /&gt;
  #include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
  int main(void) {&lt;br /&gt;
    printf(&amp;quot;1 Mississippi\n&amp;quot;);&lt;br /&gt;
    printf(&amp;quot;2 Mississippi\n&amp;quot;);&lt;br /&gt;
        -&lt;br /&gt;
        -&lt;br /&gt;
        -&lt;br /&gt;
    printf(&amp;quot;499 Mississippi\n&amp;quot;);&lt;br /&gt;
    printf(&amp;quot;500 Mississippi\n&amp;quot;);&lt;br /&gt;
    return 0;&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
With the power of a metaprogramming language we can write another program that writes this program automatically.&lt;br /&gt;
 &lt;br /&gt;
Ruby code:&lt;br /&gt;
&lt;br /&gt;
  File.open('mississippi.c', 'w') do |output|&lt;br /&gt;
   output.puts '#include &amp;lt;stdio.h&amp;gt;'&lt;br /&gt;
   output.puts 'int main(void) {'&lt;br /&gt;
     1.upto(500) do |i|&lt;br /&gt;
       output.puts &amp;quot;    printf(\&amp;quot;#{i} &amp;quot; +&lt;br /&gt;
       &amp;quot;Mississippi\\n\&amp;quot;);&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
   output.puts '    return 0;'&lt;br /&gt;
   output.puts '}'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
This code creates a file called mississippi.c with the expected 500+ lines of C source code.Here, mississippi.c is the generated code and ruby code is the metaprogram.&lt;br /&gt;
&lt;br /&gt;
== Applications of Metaprogramming ==&lt;br /&gt;
&lt;br /&gt;
Metaprogramming is an attractive technique needed when one needs to alter the behavior of a program at run time. Due to its generative nature, it has numerous applications in program development. It can achieve program development without rewriting boiler-plate code [http://en.wikipedia.org/wiki/Boilerplate_text] all the time, ensuring efficiency, increasing modularity and minimizing inconsistent implementation errors. Program generators and program analyzers are the two main categories of meta programs. Metaprograms can be compilers, interpreters, type checkers etc. Some commonly used applications include using a program that outputs source code to - &lt;br /&gt;
* generate sine/cosine/whatever lookup tables&lt;br /&gt;
* to extract a source-form representation of a binary file&lt;br /&gt;
* to compile your bitmaps into fast display routines&lt;br /&gt;
* to extract documentation, initialization/finalization code, description tables, as well as normal code from the same source files&lt;br /&gt;
* to have customized assembly code, generated from a perl/shell/scheme script that does arbitrary processing&lt;br /&gt;
* to propagate data defined at one point only into several cross-referencing tables and code chunks. &lt;br /&gt;
&lt;br /&gt;
Programmers can focus more on the main business logic and new features to be implemented rather than writing repetitive chunks of code (e.g. setups, stubs)[1].&lt;br /&gt;
&lt;br /&gt;
= Typing in Programming Languages =&lt;br /&gt;
&lt;br /&gt;
Earlier programming languages [e.g. Assembly] were written such that each machine level function was reflected in the program code. With advancement in programming languages a certain level of abstraction was reached wherein lower level details were abstracted with one functional unit of work and represented by fewer lines of code e.g. primitive variables are represented with higher level abstract classes. With this abstraction arose a need for checking the validity of operations that could be performed with these abstractions in place.&lt;br /&gt;
&lt;br /&gt;
Typing in programming languages is property of operations and variables in the language that ensure that certain kinds of values that are invalid are not used in operations with each other. Errors related to these are known as type errors. Type checking is the process of verifying and enforcing the constraints of types. Compile time type checking also known as static type checking. Run time type checking is known as dynamic type checking. If a language specification requires its typing rules strongly (i.e., more or less allowing only those automatic type conversions which do not lose information), one can refer to the process as strongly typed, if not, as weakly typed.[http://en.wikipedia.org/wiki/Type_system]&lt;br /&gt;
The above classification can be represented as - &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Image:Meta_2.jpg]]&lt;br /&gt;
&lt;br /&gt;
== Statically Typed Programming Languages ==&lt;br /&gt;
&lt;br /&gt;
Statically typed languages ensure that a fixed type is assigned by the programmer to every variable and parameter. Thus, every expression type can be deduced and type checked during compilation. Static languages try to fix most errors during compile time and strive to minimize failures during run time. Due to this there are many type constraints on the programmer while coding.  At run time, the program uses the classes that it has been given and in this way statically typed languages make distinctions between what happens at compile time and what happens at run time. Examples of statically typed languages are C, C++, Java, C#.&lt;br /&gt;
&lt;br /&gt;
== Dynamically Typed Programming Languages ==&lt;br /&gt;
&lt;br /&gt;
In dynamically typed languages, the variables and parameters do not have a designated type and may take different values at different times. In all the operations, the operands must be type checked at runtime just before performing the operation. Dynamically typed languages don’t need to make a distinction between classes created at compile time and classes provided.  It is possible to define classes at run time and in fact, classes are always defined at run time. These eliminate many developer constraints by avoiding the need of book keeping, declarations etc. Due to this flexibility these languages make an ideal candidate for prototyping and are widely used in agile development environments. However, dynamic languages are known to have performance issues. Static languages have code optimization features at compile time, but dynamic languages allow runtime code optimizations only. [http://www.slideshare.net/aminbandeali/dynamically-and-statically-typed-languages] In dynamically typed languages,  the interpreter deduces type and type conversions, this makes development time faster, but it also can provoke runtime failures. These runtime failures are caught early on during compile time for statically typed languages.&lt;br /&gt;
Examples of dynamically typed languages include Perl, Python,  JavaScript, PHP, Ruby, Groovy.&lt;br /&gt;
&lt;br /&gt;
= Metaprogramming in statically typed languages =&lt;br /&gt;
&lt;br /&gt;
In safety languages [syntactically verbose], metaprogramming is not a standard feature, it can however be achieved. Also, static typing in meta-programs has a number of advantages. In addition to guaranteeing that the meta-program encounters no type-errors while manipulating object-programs, a statically typed metaprogramming language can also guarantee that any of the object-programs generated by the meta-program are also type-correct. A disadvantage of these type system is that (in case of meta-programming languages with weaker type systems) they sometime may be too restrictive in object-programs that the programmer is allowed to construct.&lt;br /&gt;
&lt;br /&gt;
== Techniques and Packages ==&lt;br /&gt;
&lt;br /&gt;
Many language features can be leveraged to achieve some form of characteristics needed to achieve metaprogramming. For instance, languages that support  reflection also allow for dynamic code generation.  e.g. In Microsoft .NET Framework use of &amp;quot;System.Reflection.Emit&amp;quot; namespace is used to generate types and methods at runtime. &lt;br /&gt;
&lt;br /&gt;
=== Reflection ===&lt;br /&gt;
&lt;br /&gt;
Reflection is a valuable language feature to facilitate metaprogramming. Reflection is defined as the ability of a programming language to be its own meta-language. Thus, reflection is writing programs that manipulate other programs or themselves. [http://www.developer.com/java/web/article.php/3504271/Java-Reflection-in-Action.htm] &amp;lt;br&amp;gt;&lt;br /&gt;
e.g. In Java, reflection enables to discover information about the loaded classes:&lt;br /&gt;
* Fields,&lt;br /&gt;
* Methods and constructors&lt;br /&gt;
* Generics information&lt;br /&gt;
* Metadata annotations&lt;br /&gt;
It also enables to use these metaobjects to their instances in run time environment.&lt;br /&gt;
E.g. Method.invoke(Object o, Object… args)&lt;br /&gt;
With the Java reflection API, you can interrogate an object to get all sorts of information about its class. &lt;br /&gt;
&lt;br /&gt;
Consider the following simple example:   &lt;br /&gt;
  public class HelloWorld {&lt;br /&gt;
    public void printName() {&lt;br /&gt;
      System.out.println(this.getClass().getName());&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
The line&lt;br /&gt;
  (new HelloWorld()).printName();&lt;br /&gt;
sends the string HelloWorld to standard out. Now let x be an instance of HelloWorld or one of its subclasses. The line&lt;br /&gt;
  x.printName();&lt;br /&gt;
sends the string naming the class to standard out.&lt;br /&gt;
&lt;br /&gt;
The printName method examines the object for its class (this.getClass()). In doing so, the decision of what to print is made by delegating to the object's class. The method acts on this decision by printing the returned name. Without being overridden, the printName method behaves differently for each subclass than it does for HelloWorld. The printName method is flexible; it adapts to the class that inherits it, causing the change in behavior.&lt;br /&gt;
&lt;br /&gt;
=== Annotations ===&lt;br /&gt;
&lt;br /&gt;
Annotations are a metaprogramming facility that allow the code to be marked with defined tags. Many APIs require a fair amount of boilerplate code. This boilerplate could be generated automatically by a tool if the program were “decorated” with annotations indicating which methods were remotely accessible. Metadata provided using annotations is beneficial for documentation, compiler checking, and code analysis. One can use this metadata to indicate if methods are dependent on other methods, if they are incomplete, if a certain class must reference another class, and so on. It is used by the compiler to perform some basic compile-time checking. For example there is a override annotation that lets you specify that a method overrides another method from a superclass. At this, the Java compiler will ensure that the behavior you indicate in your metadata actually happens at a code level as well.&lt;br /&gt;
&lt;br /&gt;
An “annotation” has an “annotation type” associated with it which is used for defining it. It is used when you want to create a custom annotation. The type is the actual construct used, and the annotation is the specific usage of that type. An annotation type definition takes an &amp;quot;at&amp;quot; (@) sign, followed by the interface keyword plus the annotation name. On the other hand, an annotation takes the form of an &amp;quot;at&amp;quot; sign (@), followed by the annotation type [http://www.developer.com/java/other/article.php/3556176/An-Introduction-to-Java-Annotations.htm].&lt;br /&gt;
&lt;br /&gt;
Example to Define an Annotation (Annotation type)&lt;br /&gt;
   &lt;br /&gt;
  public @interface MyAnnotation {&lt;br /&gt;
    String doSomething();}&lt;br /&gt;
   Example to Annotate Your Code (Annotation)&lt;br /&gt;
   MyAnnotation (doSomething=&amp;quot;What to do&amp;quot;)&lt;br /&gt;
   public void mymethod() {&lt;br /&gt;
   ....&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
==== Annotation Types ====&lt;br /&gt;
There are three annotation types:&lt;br /&gt;
* '''Marker:''' Marker type annotations have no elements, except the annotation name itself.&lt;br /&gt;
Example:&lt;br /&gt;
  public @interface MyAnnotation {&lt;br /&gt;
  } &lt;br /&gt;
Usage:&lt;br /&gt;
  @MyAnnotation&lt;br /&gt;
  public void mymethod() {&lt;br /&gt;
   ....&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
* '''Single-Element:''' Single-element, or single-value type, annotations provide a single piece of data only. This can be represented with a data=value pair or, simply with the value (a shortcut syntax) only, within parenthesis.&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
  public @interface MyAnnotation&lt;br /&gt;
  {&lt;br /&gt;
    String doSomething();&lt;br /&gt;
  } &lt;br /&gt;
&lt;br /&gt;
Usage:&lt;br /&gt;
  @MyAnnotation (&amp;quot;What to do&amp;quot;)&lt;br /&gt;
  public void mymethod() {&lt;br /&gt;
   ....&lt;br /&gt;
  } &lt;br /&gt;
&lt;br /&gt;
* '''Full-value or multi-value:''' Full-value type annotations have multiple data members. Therefore, you must use a full data=value parameter syntax for each member.&lt;br /&gt;
Example:&lt;br /&gt;
  public @interface MyAnnotation {&lt;br /&gt;
    String doSomething();&lt;br /&gt;
    int count; String date();&lt;br /&gt;
  } &lt;br /&gt;
Usage:&lt;br /&gt;
  @MyAnnotation (doSomething=&amp;quot;What to do&amp;quot;, count=1,&lt;br /&gt;
              date=&amp;quot;09-09-2005&amp;quot;)&lt;br /&gt;
  public void mymethod() {&lt;br /&gt;
&lt;br /&gt;
=== Generics ===&lt;br /&gt;
&lt;br /&gt;
Generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated  when needed for specific types provided as parameters. [http://en.wikipedia.org/wiki/Generic_programming] Java Generics are primarily a way for library authors to write something once, which users can customize to their own types. They allow the creation of classes and methods that work in the same way on different types of objects. The term &amp;quot;generic&amp;quot; comes from the idea that we'd like to be able to write general algorithms that can be broadly reused for many types of objects rather than having to adapt our code to fit each circumstance.&lt;br /&gt;
&lt;br /&gt;
Generics add a way to specify concrete types to general purpose classes and methods that operated on object before. A Java collection is a flexible data structure that can hold heterogeneous objects where the elements may have any reference type. When you take an element out of a collection, you must cast it to the type of element that is stored in the collection. Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that the collection has been used consistently and can insert the correct casts on values being taken out of the collection.[5] Generics are implemented by type erasure: generic type information is present only at compile time, after which it is erased by the compiler. The main advantage of this approach is that it provides total interoperability between generic code and legacy code that uses non-parametrized types (which are technically known as raw types).&lt;br /&gt;
&lt;br /&gt;
Consider a non-generic example:&lt;br /&gt;
   //This program removes 4-letter words from c. Elements must be strings&lt;br /&gt;
   static void expurgate(Collection c)  &lt;br /&gt;
   {    &lt;br /&gt;
        for (Iterator i = c.iterator(); i.hasNext(); )      &lt;br /&gt;
        if (((String) i.next()).length() == 4)        &lt;br /&gt;
        i.remove();&lt;br /&gt;
    }&lt;br /&gt;
Here is the same example modified to use generics:&lt;br /&gt;
   //This program removes the 4-letter words from c&lt;br /&gt;
  static void expurgate(Collection&amp;lt;String&amp;gt; c) &lt;br /&gt;
  {    &lt;br /&gt;
    for (Iterator&amp;lt;String&amp;gt; i = c.iterator(); i.hasNext(); )&lt;br /&gt;
    if (i.next().length() == 4)&lt;br /&gt;
    i.remove();&lt;br /&gt;
  }&lt;br /&gt;
The declaration above reads as “Collection of String c.” Collection is a generic class that takes ‘String’ as its type parameter. The code using generics is clearer and safer. Unsafe cast and a number of extra parentheses have been eliminated. More importantly, we have moved part of the specification of the method from a comment to its signature, so the compiler can verify at compile time that the type constraints are not violated at run time.[http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf]&lt;br /&gt;
&lt;br /&gt;
=== Template Metaprogramming ===&lt;br /&gt;
Template metaprogramming(TMP) or Static Metaprogramming is a technique that allows the execution of programs at compile-time. It uses extremely early binding.&lt;br /&gt;
A primary requirement for a metaprogramming language is providing high-level abstractions to hide the internal representation of base programs.[http://lcgapp.cern.ch/project/architecture/ReflectionPaper.pdf] Each template language is specific for a base language and is generated from it. In this sense, a language of templates is a superset of the base language. Thus templates are abstractions that encapsulate a program pattern written by example.  This concept has been explained in detail in [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch2_S24_rm#C.2B.2B_Template_Metaprogramming section 3.2.5]&lt;br /&gt;
&lt;br /&gt;
Uses of template metaprogramming:&lt;br /&gt;
* Compile-time dimensional analysis&lt;br /&gt;
* Multiple dispatch&lt;br /&gt;
* Design patterns&lt;br /&gt;
* Code optimization &lt;br /&gt;
* Lexing and parsing&lt;br /&gt;
&lt;br /&gt;
== Packages ==&lt;br /&gt;
&lt;br /&gt;
=== Javassist (Java Programming Assistant) ===&lt;br /&gt;
&lt;br /&gt;
Javassist is a Java library providing means to manipulate the Java bytecode of an application. It provides the support for structural reflection, i.e. the ability to change the implementation of a class at runtime. [http://www.csg.is.titech.ac.jp/~chiba/javassist/] Javassist is explicit metaprogramming, in which the metalanguage is Java. It is a load-time reflective system for Java which enables Java programs to define a new class at runtime and to modify a class file when the JVM loads it. Unlike other similar bytecode editors, Javassist provides two levels of API: source level and bytecode level.&lt;br /&gt;
&lt;br /&gt;
If the users use the source-level API, they can edit a class file without knowledge of the specifications of the Java bytecode. They do not have to even write an inserted bytecode sequence; Javassist instead can compile a fragment of source text on line (for example, just a single statement). This ease of use is a unique feature of Javassit against other tools. One can even specify inserted bytecode in the form of source text and Javassist compiles it on the fly. On the other hand, the bytecode-level API allows the users to directly edit a class file as other editors. Thus it makes Java bytecode manipulation simple.&lt;br /&gt;
&lt;br /&gt;
Javassist has the following applications:&lt;br /&gt;
* Aspect Oriented Programming:     Javassist can be a good tool for introducing new methods into a class and for inserting before/after/around advice at the both caller and callee sides.&lt;br /&gt;
* Reflection:     One of applications of Javassist is runtime reflection; Javassist enables Java programs to use a metaobject that controls method calls on base-level objects. No specialized compiler or virtual machine are needed.&lt;br /&gt;
* Remote method invocation:     Another application is remote method invocation. Javassist enables applets to call a method on a remote object running on the web server. Unlike the Java RMI, the programmer does notneed a stub compiler such as rmic; the stub code is dynamically produced by Javassist.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
  BufferedInputStream fin = new BufferedInputStream(new FileInputStream(&amp;quot;Point.class&amp;quot;));&lt;br /&gt;
  ClassFile cf = new ClassFile(new DataInputStream(fin));&lt;br /&gt;
&lt;br /&gt;
A ClassFile object can be written back to a class file. write() in ClassFile writes the contents of the class file to a given DataOutputStream. ClassFile provides addField() and addMethod() for adding a field or a method (note that a constructor is regarded as a method at the bytecode level). It also provides addAttribute() for adding an attribute to the class file.&lt;br /&gt;
&lt;br /&gt;
To examine every bytecode instruction in a method body, CodeIterator is useful. A CodeIterator object allows you to visit every bytecode instruction one by one from the beginning to the end. To otbain this object, do as follows:&lt;br /&gt;
&lt;br /&gt;
     ClassFile cf = ... ;&lt;br /&gt;
     MethodInfo minfo = cf.getMethod(&amp;quot;move&amp;quot;);    // we assume move is not overloaded.&lt;br /&gt;
     CodeAttribute ca = minfo.getCodeAttribute();&lt;br /&gt;
     CodeIterator i = ca.iterator();&lt;br /&gt;
&lt;br /&gt;
Other extensions are being developed to include reflective systems for C++ and Java e.g. OpenC++ and OpenJava which are extensible preprocessors based on compile-time reflection in C++ and Java respectively.&lt;br /&gt;
&lt;br /&gt;
=== JRuby ===&lt;br /&gt;
&lt;br /&gt;
JRuby is a complete implementation of Ruby in Java. The scripting and functional features of the Ruby language can be used by Java developers.[http://depth-first.com/articles/2006/10/24/metaprogramming-with-ruby-mapping-java-packages-onto-ruby-modules] Simple metaprogramming techniques can be  extended from  Ruby so that Java packages are mapped onto to Ruby modules. This would be something like a Ruby-Java Bridge, since JRuby can be run from any platform with a JVM.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
Using JRuby API calling JRuby from Java&lt;br /&gt;
&lt;br /&gt;
    import org.jruby.*;&lt;br /&gt;
    public class SimpleJRubyCall {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
        Ruby runtime = Ruby.getDefaultInstance();&lt;br /&gt;
    runtime.evalScript(“puts 1+2”);&lt;br /&gt;
      }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
With metaprogramming using JRuby one can&lt;br /&gt;
* add methods to class,&lt;br /&gt;
*  add instance methods&lt;br /&gt;
*  add to have Java classes&lt;br /&gt;
&lt;br /&gt;
Since metaprogramming empowers the programmer to create domain specific languages(DSL), the ones created by JRuby can always leverage Java libraries to build wrapper functionalities.&lt;br /&gt;
e.g. Simple JRuby DSL on top of HtmlUnit&lt;br /&gt;
&lt;br /&gt;
=== AspectJ ===&lt;br /&gt;
Another library worth mentioning here is AspectJ. It enforces the aspect oriented programming (AOP) approach in Java. Aspect oriented programming is a complimentary programming paradigm to object oriented programming and is used to improve the modularity of software systems. Thus, while object oriented programming is great for modeling common behavior on a hierarchy of objects, aspect oriented programming allows you to define cross-cutting concerns by adding direct semantics and can be applied across heterogeneous object models. [http://static.springsource.org/spring/docs/2.0.x/reference/aop.html] Applications of aspect oriented programming include logging, instrumenting and debugging. &lt;br /&gt;
&lt;br /&gt;
In object oriented programs, the natural unit of modularity is the class. In AspectJ, aspects modularize concerns that affect more than one class. In addition to classes, aspect oriented programming uses 'aspects'. Aspects enable modularization of crosscutting concerns such as transaction management that cut across multiple types and objects. Thus, AspectJ package achieves metaprogramming features with more controllability.&lt;br /&gt;
&lt;br /&gt;
AspectJ introduces declaring aspects in the statically typed language Java by using 3 key concepts -&lt;br /&gt;
* Join Points - well defined points in program execution&lt;br /&gt;
* Advice - defines additional code to be executed around join points&lt;br /&gt;
* Pointcut - define those points in the source code of a program where an advice will be applied&lt;br /&gt;
&lt;br /&gt;
The core task of AspectJ's advice weaver is to statically transform a program so that at runtime it will behave according to the AspectJ language semantics. The AspectJ weaver takes class files as input and produces class files as output. The weaving process itself can take place at one of three different times: compile-time, post-compile time, and load-time. These two java files are 'woven' together by compiler i.e. the class and the aspect behavior are tied together. This is also known as 'plugging-in' the aspect. [http://oreilly.com/catalog/9780596006549]&lt;br /&gt;
&lt;br /&gt;
Example - Simple tracing/logging&lt;br /&gt;
&lt;br /&gt;
Consider the HelloWorld class below which implements an application that simply displays &amp;quot;Hello World!&amp;quot; on the standard output.&lt;br /&gt;
 package helloworld; &lt;br /&gt;
 class HelloWorld {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
            new HelloWorld().printMessage();&lt;br /&gt;
    }   &lt;br /&gt;
    void printMessage() {&lt;br /&gt;
            System.out.println(&amp;quot;Hello world!&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Consider another Java source file with an aspect definition as follows - &lt;br /&gt;
 package helloworld;&lt;br /&gt;
 aspect Trace of eachobject(instanceof(HelloWorld)) {&lt;br /&gt;
    pointcut printouts(): receptions(void printMessage());&lt;br /&gt;
    before(): printouts() {&lt;br /&gt;
              System.out.println(&amp;quot;*** Entering printMessage ***&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    after():  printouts() {&lt;br /&gt;
              System.out.println(&amp;quot;*** Exiting printMessage ***&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In above example, the Trace aspect injects tracing messages before and after method main of class HelloWorld. If one does not want tracing, one can simply leave the aspect out and plug it in as and when required.&lt;br /&gt;
&lt;br /&gt;
In contrast to reflection[low level], AspectJ provides more carefully controlled power, drawing on the rules learned from object-oriented development to encourage a clean and understandable program structure. An aspect imposes behavior on a class, rather than a class requesting behavior from an aspect. An aspect can modify a class without needing to edit that class - also known as 'reverse inheritance'.&lt;br /&gt;
&lt;br /&gt;
=== MetaJ ===&lt;br /&gt;
&lt;br /&gt;
MetaJ is another package that supports metaprogramming in the Java language. A MetaJ program consists of the Java code with special metaprogramming declarations that will control how the output code is created. It uses templates and reflection. Templates are abstractions that encapsulate a program pattern written by example. Templates are translated to Java classes, so they can be accessed in the metaprogram. Accessing patterns by example inside ordinary Java programs is a major feature of MetaJ programming. [http://www.jucs.org/jucs_10_7/metaj_an_extensible_environment] &lt;br /&gt;
&lt;br /&gt;
Language Dependency:&lt;br /&gt;
MetaJ comprises of a set of concepts that are independent of the base language. These are syntax trees, code references, code iterators and code templates. A framework is defined which in which features common to most languages are abstracted. This supports independence from base language. Thus, generic operations can be defined and components that are language dependent can be plugged onto it. &lt;br /&gt;
&lt;br /&gt;
Execution Flow Representation:&lt;br /&gt;
&lt;br /&gt;
[[Image:Meta_3.jpg]]&lt;br /&gt;
&lt;br /&gt;
Example: &lt;br /&gt;
&lt;br /&gt;
Template :  SampleTempl&lt;br /&gt;
&lt;br /&gt;
 package myTempl; &lt;br /&gt;
 language = Java // base language plug­in&lt;br /&gt;
 template #CompilationUnit SampleTempl{ &lt;br /&gt;
 #[#PackageDeclaration:pck]# &lt;br /&gt;
 #[#ImportDeclarationList:imps]# &lt;br /&gt;
 class SampleTempl { ... } &lt;br /&gt;
 #TypeDeclaration:td &lt;br /&gt;
 } &lt;br /&gt;
&lt;br /&gt;
Instance of Template : Java Code &lt;br /&gt;
&lt;br /&gt;
 package myTempl; &lt;br /&gt;
 import metaj.framework.AbstractTemplate; &lt;br /&gt;
 public class SampleTempl extends AbstractTemplate{ &lt;br /&gt;
 public final Reference imps, td, pck;&lt;br /&gt;
 ... // Implementation of superclass abstract methods&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Java SDK7 has added support for dynamic typing and metaprogramming and includes MetaJ implementation.&lt;br /&gt;
&lt;br /&gt;
=== C++ Template Metaprogramming ===&lt;br /&gt;
&lt;br /&gt;
In C++, [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch2_S24_rm#Template_Metaprogramming static metaprogramming] is implemented with the help of reflection. The most important implementation of reflection in C++ is using the feature of run time type-identification (RTTI) [http://depth-first.com/articles/2006/10/24/metaprogramming-with-ruby-mapping-java-packages-onto-ruby-modules]. RTTI is a system that keeps information about an object's data type in memory at run time. Run-time type information can apply to simple data types, such as integers and characters, or to generic objects. Enabling RTTI in C++ allows the use of dynamic_cast&amp;lt;&amp;gt; operation, the typeid operator or exceptions [http://en.wikipedia.org/wiki/Run-time_type_information].&lt;br /&gt;
&lt;br /&gt;
The template mechanism in C++ allows defining parametrized classes and functions. Templates together with other C++ features constitute a Turing-complete, compile-time sub- language of C++. A Turing-complete language is a language with at least a conditional and a looping construct. C++ can be considered to be a two-level language since a C++ program may contain both static code, which is evaluated at compile time, and dynamic code, which is executed at run time. Template meta-programs are the part of a C++ source that is executed during compilation. A meta-program can access information about types not generally available to ordinary programs [http://lcgapp.cern.ch/project/architecture/ReflectionPaper.pdf].&lt;br /&gt;
&lt;br /&gt;
Given below is an example of how to use templates for writing a common recursive factorial program:&lt;br /&gt;
  template&amp;lt;int count&amp;gt;&lt;br /&gt;
  class FACTOR{&lt;br /&gt;
  public:&lt;br /&gt;
      enum {RESULT = count * FACTOR&amp;lt;count-1&amp;gt;::RESULT};&lt;br /&gt;
       };&lt;br /&gt;
  class FACTOR&amp;lt;1&amp;gt;{&lt;br /&gt;
  public:&lt;br /&gt;
      enum {RESULT = 1};&lt;br /&gt;
       };&lt;br /&gt;
&lt;br /&gt;
If we write this-&lt;br /&gt;
  int j = FACTOR&amp;lt;5&amp;gt;::RESULT;&lt;br /&gt;
&lt;br /&gt;
The above line will calculate the value of 5 factorial. As we instantiate FACTOR&amp;lt;5&amp;gt; the definition of this class depends on FACTOR&amp;lt;4&amp;gt;, which in turn depend on FACTOR&amp;lt;3&amp;gt; and so on. The compiler needs to create all these classes until the template specialization FACTOR&amp;lt;1&amp;gt; is reached. This means the entire recursion is done by the compiler during compile time and it uses the result as if it is a constant.&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Dynamically typed languages are best suited to provide support for metaprogramming due to their inherent nature of easily overcoming distinction between code and data e.g. Lisp provides this feature of interchangeability.  Code and data are both represented in Lisp as lists, so any list can easily be treated as either code or data.  &lt;br /&gt;
It’s simple, therefore, to manipulate code as data, and then execute it – either via EVAL or by returning it as the result of a macro expansion. [3]&lt;br /&gt;
&lt;br /&gt;
Thus, statically typed languages achieve metaprogramming using various techniques and tools to achieve the level of flexibility that dynamic languages provide immanently.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://en.wikipedia.org/wiki/Metaprogramming Metaprogramming]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Boilerplate_text Boilerplate Text]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Type_system Type System]&lt;br /&gt;
*[4]  [http://www.slideshare.net/aminbandeali/dynamically-and-statically-typed-languages Bandeali, M. 2009. ''Dynamically and Statically typed languages'']&lt;br /&gt;
*[5]  [http://www.developer.com/java/web/article.php/3504271/Java-Reflection-in-Action.htm Java Reflection in Action]&lt;br /&gt;
*[6]  [http://www.developer.com/java/other/article.php/3556176/An-Introduction-to-Java-Annotations.htm An Introduction to Java Annotations]&lt;br /&gt;
*[7]  [http://en.wikipedia.org/wiki/Generic_programming Generic Programming]&lt;br /&gt;
*[8]  [http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf Haapakorpi, M. ''Metaprogramming in Java'']&lt;br /&gt;
*[9]  [http://lcgapp.cern.ch/project/architecture/ReflectionPaper.pdf Attardi, G., Cisternino, A. ''Reflection support by means of template metaprogramming'']&lt;br /&gt;
*[10] [http://www.csg.is.titech.ac.jp/~chiba/javassist/ Javassist]&lt;br /&gt;
*[11] [http://depth-first.com/articles/2006/10/24/metaprogramming-with-ruby-mapping-java-packages-onto-ruby-modules Metaprogramming with Ruby: Mapping Java Packages Onto Ruby Modules]&lt;br /&gt;
*[12] [http://static.springsource.org/spring/docs/2.0.x/reference/aop.html Aspect Oriented Programming with Spring]&lt;br /&gt;
*[13] [http://oreilly.com/catalog/9780596006549 Miles, R. 2004 ''AspectJ Cookbook'' O'Reilly Media]&lt;br /&gt;
*[14] [http://www.jucs.org/jucs_10_7/metaj_an_extensible_environment Oliveira, A.A., Braga, T.H, Maia, M.A., Bigonha and R.S. 2004. MetaJ: An Extensible Environment for Metaprogramming in Java, ''Journal of Universal Computer Science, vol. 10, no. 7 (2004), 872-891'' &lt;br /&gt;
*[15] http://depth-first.com/articles/2006/10/24/metaprogramming-with-ruby-mapping-java-packages-onto-ruby-modules&lt;br /&gt;
*[16] http://en.wikipedia.org/wiki/Run-time_type_information&lt;br /&gt;
*[17] http://lcgapp.cern.ch/project/architecture/ReflectionPaper.pdf&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://www.cs.tut.fi/~kk/webstuff/MetaprogrammingCpp.pdf Metaprogramming in C++]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Automatic_programming Automatic/Generative Programming]&lt;br /&gt;
*[http://www.slideshare.net/dogangoko/new-features-of-java7-se-presentation News in the upcoming Java 7]&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch2_S24_rm&amp;diff=36367</id>
		<title>CSC/ECE 517 Fall 2010/ch2 S24 rm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch2_S24_rm&amp;diff=36367"/>
		<updated>2010-09-30T23:37:21Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Metaprogramming in Statically Typed Languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;I'd rather write programs that write programs than write programs&amp;quot; - Richard Sites''&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Metaprogramming is an inherent feature of dynamically typed languages [e.g. Ruby]. However, achieving metaprogramming in statically typed languages [e.g. Java] becomes complex due to compile time abstraction verification. In this topic, we explore how tools and packages are usedto implement metaprogramming in statically typed languages .&lt;br /&gt;
&lt;br /&gt;
== Metaprogramming ==&lt;br /&gt;
&lt;br /&gt;
Metaprogramming is a programming technique of writing computer programs that write or manipulate other programs or themselves, as data. [http://en.wikipedia.org/wiki/Metaprogramming] In other words, it is a programming technique of writing programs with a higher level of abstraction to make it appear as generative programming.  &lt;br /&gt;
&lt;br /&gt;
Metaprogramming involves two kinds of languages-&lt;br /&gt;
* '''Meta-language''' is the language in which meta-programs, which construct or manipulate other programs, are written. &lt;br /&gt;
* '''Object-language''' is the language of programs being manipulated. &lt;br /&gt;
This makes them ‘meta level programs’ whose problem domain are other ‘base level programs’.&lt;br /&gt;
&lt;br /&gt;
[[Image:Meta_1.jpg]]&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own metalanguage is called reflection or reflexivity.&lt;br /&gt;
&lt;br /&gt;
Simple example of a metaprogram:&lt;br /&gt;
&amp;lt;br&amp;gt;Let us consider a totally fabricated example for our understanding at very high level. Suppose we need to write a C program that printed the following 500 lines of text with a restriction that the program could not use any kind of loop or goto instruction.&lt;br /&gt;
&lt;br /&gt;
Output expected:&lt;br /&gt;
&lt;br /&gt;
  1 Mississippi&lt;br /&gt;
  2 Mississippi&lt;br /&gt;
  3 Mississippi&lt;br /&gt;
  4 Mississippi&lt;br /&gt;
  ...&lt;br /&gt;
  499 Mississippi&lt;br /&gt;
  500 Mississippi&lt;br /&gt;
&lt;br /&gt;
In C this would be then coded as:&lt;br /&gt;
&lt;br /&gt;
  #include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
  int main(void) {&lt;br /&gt;
    printf(&amp;quot;1 Mississippi\n&amp;quot;);&lt;br /&gt;
    printf(&amp;quot;2 Mississippi\n&amp;quot;);&lt;br /&gt;
        -&lt;br /&gt;
        -&lt;br /&gt;
        -&lt;br /&gt;
    printf(&amp;quot;499 Mississippi\n&amp;quot;);&lt;br /&gt;
    printf(&amp;quot;500 Mississippi\n&amp;quot;);&lt;br /&gt;
    return 0;&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
With the power of a metaprogramming language we can write another program that writes this program automatically.&lt;br /&gt;
 &lt;br /&gt;
Ruby code:&lt;br /&gt;
&lt;br /&gt;
  File.open('mississippi.c', 'w') do |output|&lt;br /&gt;
   output.puts '#include &amp;lt;stdio.h&amp;gt;'&lt;br /&gt;
   output.puts 'int main(void) {'&lt;br /&gt;
     1.upto(500) do |i|&lt;br /&gt;
       output.puts &amp;quot;    printf(\&amp;quot;#{i} &amp;quot; +&lt;br /&gt;
       &amp;quot;Mississippi\\n\&amp;quot;);&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
   output.puts '    return 0;'&lt;br /&gt;
   output.puts '}'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
This code creates a file called mississippi.c with the expected 500+ lines of C source code.Here, mississippi.c is the generated code and ruby code is the metaprogram.&lt;br /&gt;
&lt;br /&gt;
== Applications of Metaprogramming ==&lt;br /&gt;
&lt;br /&gt;
Metaprogramming is an attractive technique needed when one needs to alter the behavior of a program at run time. Due to its generative nature, it has numerous applications in program development. It can achieve program development without rewriting boiler-plate code [http://en.wikipedia.org/wiki/Boilerplate_text] all the time, ensuring efficiency, increasing modularity and minimizing inconsistent implementation errors. Program generators and program analyzers are the two main categories of meta programs. Metaprograms can be compilers, interpreters, type checkers etc. Some commonly used applications include using a program that outputs source code to - &lt;br /&gt;
* generate sine/cosine/whatever lookup tables&lt;br /&gt;
* to extract a source-form representation of a binary file&lt;br /&gt;
* to compile your bitmaps into fast display routines&lt;br /&gt;
* to extract documentation, initialization/finalization code, description tables, as well as normal code from the same source files&lt;br /&gt;
* to have customized assembly code, generated from a perl/shell/scheme script that does arbitrary processing&lt;br /&gt;
* to propagate data defined at one point only into several cross-referencing tables and code chunks. &lt;br /&gt;
&lt;br /&gt;
Programmers can focus more on the main business logic and new features to be implemented rather than writing repetitive chunks of code (e.g. setups, stubs)[1].&lt;br /&gt;
&lt;br /&gt;
= Typing in Programming Languages =&lt;br /&gt;
&lt;br /&gt;
Earlier programming languages [e.g. Assembly] were written such that each machine level function was reflected in the program code. With advancement in programming languages a certain level of abstraction was reached wherein lower level details were abstracted with one functional unit of work and represented by fewer lines of code e.g. primitive variables are represented with higher level abstract classes. With this abstraction arose a need for checking the validity of operations that could be performed with these abstractions in place.&lt;br /&gt;
&lt;br /&gt;
Typing in programming languages is property of operations and variables in the language that ensure that certain kinds of values that are invalid are not used in operations with each other. Errors related to these are known as type errors. Type checking is the process of verifying and enforcing the constraints of types. Compile time type checking also known as static type checking. Run time type checking is known as dynamic type checking. If a language specification requires its typing rules strongly (i.e., more or less allowing only those automatic type conversions which do not lose information), one can refer to the process as strongly typed, if not, as weakly typed.[http://en.wikipedia.org/wiki/Type_system]&lt;br /&gt;
The above classification can be represented as - &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Image:Meta_2.jpg]]&lt;br /&gt;
&lt;br /&gt;
== Statically Typed Programming Languages ==&lt;br /&gt;
&lt;br /&gt;
Statically typed languages ensure that a fixed type is assigned by the programmer to every variable and parameter. Thus, every expression type can be deduced and type checked during compilation. Static languages try to fix most errors during compile time and strive to minimize failures during run time. Due to this there are many type constraints on the programmer while coding.  At run time, the program uses the classes that it has been given and in this way statically typed languages make distinctions between what happens at compile time and what happens at run time. Examples of statically typed languages are C, C++, Java, C#.&lt;br /&gt;
&lt;br /&gt;
== Dynamically Typed Programming Languages ==&lt;br /&gt;
&lt;br /&gt;
In dynamically typed languages, the variables and parameters do not have a designated type and may take different values at different times. In all the operations, the operands must be type checked at runtime just before performing the operation. Dynamically typed languages don’t need to make a distinction between classes created at compile time and classes provided.  It is possible to define classes at run time and in fact, classes are always defined at run time. These eliminate many developer constraints by avoiding the need of book keeping, declarations etc. Due to this flexibility these languages make an ideal candidate for prototyping and are widely used in agile development environments. However, dynamic languages are known to have performance issues. Static languages have code optimization features at compile time, but dynamic languages allow runtime code optimizations only. [http://www.slideshare.net/aminbandeali/dynamically-and-statically-typed-languages] In dynamically typed languages,  the interpreter deduces type and type conversions, this makes development time faster, but it also can provoke runtime failures. These runtime failures are caught early on during compile time for statically typed languages.&lt;br /&gt;
Examples of dynamically typed languages include Perl, Python,  JavaScript, PHP, Ruby, Groovy.&lt;br /&gt;
&lt;br /&gt;
= Metaprogramming in statically typed languages =&lt;br /&gt;
&lt;br /&gt;
In safety languages [syntactically verbose], metaprogramming is not a standard feature, it can however be achieved. Also, static typing in meta-programs has a number of advantages. In addition to guaranteeing that the meta-program encounters no type-errors while manipulating object-programs, a statically typed metaprogramming language can also guarantee that any of the object-programs generated by the meta-program are also type-correct. A disadvantage of these type system is that (in case of meta-programming languages with weaker type systems) they sometime may be too restrictive in object-programs that the programmer is allowed to construct.&lt;br /&gt;
&lt;br /&gt;
== Techniques and Packages ==&lt;br /&gt;
&lt;br /&gt;
Many language features can be leveraged to achieve some form of characteristics needed to achieve metaprogramming. For instance, languages that support  reflection also allow for dynamic code generation.  e.g. In Microsoft .NET Framework use of &amp;quot;System.Reflection.Emit&amp;quot; namespace is used to generate types and methods at runtime. &lt;br /&gt;
&lt;br /&gt;
=== Reflection ===&lt;br /&gt;
&lt;br /&gt;
Reflection is a valuable language feature to facilitate metaprogramming. Reflection is defined as the ability of a programming language to be its own meta-language. Thus, reflection is writing programs that manipulate other programs or themselves. [http://www.developer.com/java/web/article.php/3504271/Java-Reflection-in-Action.htm] &amp;lt;br&amp;gt;&lt;br /&gt;
e.g. In Java, reflection enables to discover information about the loaded classes:&lt;br /&gt;
* Fields,&lt;br /&gt;
* Methods and constructors&lt;br /&gt;
* Generics information&lt;br /&gt;
* Metadata annotations&lt;br /&gt;
It also enables to use these metaobjects to their instances in run time environment.&lt;br /&gt;
E.g. Method.invoke(Object o, Object… args)&lt;br /&gt;
With the Java reflection API, you can interrogate an object to get all sorts of information about its class. &lt;br /&gt;
&lt;br /&gt;
Consider the following simple example:   &lt;br /&gt;
  public class HelloWorld {&lt;br /&gt;
    public void printName() {&lt;br /&gt;
      System.out.println(this.getClass().getName());&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
The line&lt;br /&gt;
  (new HelloWorld()).printName();&lt;br /&gt;
sends the string HelloWorld to standard out. Now let x be an instance of HelloWorld or one of its subclasses. The line&lt;br /&gt;
  x.printName();&lt;br /&gt;
sends the string naming the class to standard out.&lt;br /&gt;
&lt;br /&gt;
The printName method examines the object for its class (this.getClass()). In doing so, the decision of what to print is made by delegating to the object's class. The method acts on this decision by printing the returned name. Without being overridden, the printName method behaves differently for each subclass than it does for HelloWorld. The printName method is flexible; it adapts to the class that inherits it, causing the change in behavior.&lt;br /&gt;
&lt;br /&gt;
=== Annotations ===&lt;br /&gt;
&lt;br /&gt;
Annotations are a metaprogramming facility that allow the code to be marked with defined tags. Many APIs require a fair amount of boilerplate code. This boilerplate could be generated automatically by a tool if the program were “decorated” with annotations indicating which methods were remotely accessible. Metadata provided using annotations is beneficial for documentation, compiler checking, and code analysis. One can use this metadata to indicate if methods are dependent on other methods, if they are incomplete, if a certain class must reference another class, and so on. It is used by the compiler to perform some basic compile-time checking. For example there is a override annotation that lets you specify that a method overrides another method from a superclass. At this, the Java compiler will ensure that the behavior you indicate in your metadata actually happens at a code level as well.&lt;br /&gt;
&lt;br /&gt;
An “annotation” has an “annotation type” associated with it which is used for defining it. It is used when you want to create a custom annotation. The type is the actual construct used, and the annotation is the specific usage of that type. An annotation type definition takes an &amp;quot;at&amp;quot; (@) sign, followed by the interface keyword plus the annotation name. On the other hand, an annotation takes the form of an &amp;quot;at&amp;quot; sign (@), followed by the annotation type [http://www.developer.com/java/other/article.php/3556176/An-Introduction-to-Java-Annotations.htm].&lt;br /&gt;
&lt;br /&gt;
Example to Define an Annotation (Annotation type)&lt;br /&gt;
   &lt;br /&gt;
  public @interface MyAnnotation {&lt;br /&gt;
    String doSomething();}&lt;br /&gt;
   Example to Annotate Your Code (Annotation)&lt;br /&gt;
   MyAnnotation (doSomething=&amp;quot;What to do&amp;quot;)&lt;br /&gt;
   public void mymethod() {&lt;br /&gt;
   ....&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
==== Annotation Types ====&lt;br /&gt;
There are three annotation types:&lt;br /&gt;
* '''Marker:''' Marker type annotations have no elements, except the annotation name itself.&lt;br /&gt;
Example:&lt;br /&gt;
  public @interface MyAnnotation {&lt;br /&gt;
  } &lt;br /&gt;
Usage:&lt;br /&gt;
  @MyAnnotation&lt;br /&gt;
  public void mymethod() {&lt;br /&gt;
   ....&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
* '''Single-Element:''' Single-element, or single-value type, annotations provide a single piece of data only. This can be represented with a data=value pair or, simply with the value (a shortcut syntax) only, within parenthesis.&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
  public @interface MyAnnotation&lt;br /&gt;
  {&lt;br /&gt;
    String doSomething();&lt;br /&gt;
  } &lt;br /&gt;
&lt;br /&gt;
Usage:&lt;br /&gt;
  @MyAnnotation (&amp;quot;What to do&amp;quot;)&lt;br /&gt;
  public void mymethod() {&lt;br /&gt;
   ....&lt;br /&gt;
  } &lt;br /&gt;
&lt;br /&gt;
* '''Full-value or multi-value:''' Full-value type annotations have multiple data members. Therefore, you must use a full data=value parameter syntax for each member.&lt;br /&gt;
Example:&lt;br /&gt;
  public @interface MyAnnotation {&lt;br /&gt;
    String doSomething();&lt;br /&gt;
    int count; String date();&lt;br /&gt;
  } &lt;br /&gt;
Usage:&lt;br /&gt;
  @MyAnnotation (doSomething=&amp;quot;What to do&amp;quot;, count=1,&lt;br /&gt;
              date=&amp;quot;09-09-2005&amp;quot;)&lt;br /&gt;
  public void mymethod() {&lt;br /&gt;
&lt;br /&gt;
=== Generics ===&lt;br /&gt;
&lt;br /&gt;
Generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated  when needed for specific types provided as parameters. [http://en.wikipedia.org/wiki/Generic_programming] Java Generics are primarily a way for library authors to write something once, which users can customize to their own types. They allow the creation of classes and methods that work in the same way on different types of objects. The term &amp;quot;generic&amp;quot; comes from the idea that we'd like to be able to write general algorithms that can be broadly reused for many types of objects rather than having to adapt our code to fit each circumstance.&lt;br /&gt;
&lt;br /&gt;
Generics add a way to specify concrete types to general purpose classes and methods that operated on object before. A Java collection is a flexible data structure that can hold heterogeneous objects where the elements may have any reference type. When you take an element out of a collection, you must cast it to the type of element that is stored in the collection. Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that the collection has been used consistently and can insert the correct casts on values being taken out of the collection.[5] Generics are implemented by type erasure: generic type information is present only at compile time, after which it is erased by the compiler. The main advantage of this approach is that it provides total interoperability between generic code and legacy code that uses non-parametrized types (which are technically known as raw types).&lt;br /&gt;
&lt;br /&gt;
Consider a non-generic example:&lt;br /&gt;
   //This program removes 4-letter words from c. Elements must be strings&lt;br /&gt;
   static void expurgate(Collection c)  &lt;br /&gt;
   {    &lt;br /&gt;
        for (Iterator i = c.iterator(); i.hasNext(); )      &lt;br /&gt;
        if (((String) i.next()).length() == 4)        &lt;br /&gt;
        i.remove();&lt;br /&gt;
    }&lt;br /&gt;
Here is the same example modified to use generics:&lt;br /&gt;
   //This program removes the 4-letter words from c&lt;br /&gt;
  static void expurgate(Collection&amp;lt;String&amp;gt; c) &lt;br /&gt;
  {    &lt;br /&gt;
    for (Iterator&amp;lt;String&amp;gt; i = c.iterator(); i.hasNext(); )&lt;br /&gt;
    if (i.next().length() == 4)&lt;br /&gt;
    i.remove();&lt;br /&gt;
  }&lt;br /&gt;
The declaration above reads as “Collection of String c.” Collection is a generic class that takes ‘String’ as its type parameter. The code using generics is clearer and safer. Unsafe cast and a number of extra parentheses have been eliminated. More importantly, we have moved part of the specification of the method from a comment to its signature, so the compiler can verify at compile time that the type constraints are not violated at run time.[http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf]&lt;br /&gt;
&lt;br /&gt;
=== Template Metaprogramming ===&lt;br /&gt;
Template metaprogramming(TMP) or Static Metaprogramming is a technique that allows the execution of programs at compile-time. It uses extremely early binding.&lt;br /&gt;
A primary requirement for a metaprogramming language is providing high-level abstractions to hide the internal representation of base programs.[http://lcgapp.cern.ch/project/architecture/ReflectionPaper.pdf] Each template language is specific for a base language and is generated from it. In this sense, a language of templates is a superset of the base language. Thus templates are abstractions that encapsulate a program pattern written by example.  This concept has been explained in detail in [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch2_S24_rm#C.2B.2B_Template_Metaprogramming section 3.2.5]&lt;br /&gt;
&lt;br /&gt;
Uses of template metaprogramming:&lt;br /&gt;
* Compile-time dimensional analysis&lt;br /&gt;
* Multiple dispatch&lt;br /&gt;
* Design patterns&lt;br /&gt;
* Code optimization &lt;br /&gt;
* Lexing and parsing&lt;br /&gt;
&lt;br /&gt;
== Packages ==&lt;br /&gt;
&lt;br /&gt;
=== Javassist (Java Programming Assistant) ===&lt;br /&gt;
&lt;br /&gt;
Javassist is a Java library providing means to manipulate the Java bytecode of an application. It provides the support for structural reflection, i.e. the ability to change the implementation of a class at runtime. [http://www.csg.is.titech.ac.jp/~chiba/javassist/] Javassist is explicit metaprogramming, in which the metalanguage is Java. It is a load-time reflective system for Java which enables Java programs to define a new class at runtime and to modify a class file when the JVM loads it. Unlike other similar bytecode editors, Javassist provides two levels of API: source level and bytecode level.&lt;br /&gt;
&lt;br /&gt;
If the users use the source-level API, they can edit a class file without knowledge of the specifications of the Java bytecode. They do not have to even write an inserted bytecode sequence; Javassist instead can compile a fragment of source text on line (for example, just a single statement). This ease of use is a unique feature of Javassit against other tools. One can even specify inserted bytecode in the form of source text and Javassist compiles it on the fly. On the other hand, the bytecode-level API allows the users to directly edit a class file as other editors. Thus it makes Java bytecode manipulation simple.&lt;br /&gt;
&lt;br /&gt;
Javassist has the following applications:&lt;br /&gt;
* Aspect Oriented Programming:     Javassist can be a good tool for introducing new methods into a class and for inserting before/after/around advice at the both caller and callee sides.&lt;br /&gt;
* Reflection:     One of applications of Javassist is runtime reflection; Javassist enables Java programs to use a metaobject that controls method calls on base-level objects. No specialized compiler or virtual machine are needed.&lt;br /&gt;
* Remote method invocation:     Another application is remote method invocation. Javassist enables applets to call a method on a remote object running on the web server. Unlike the Java RMI, the programmer does notneed a stub compiler such as rmic; the stub code is dynamically produced by Javassist.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
  BufferedInputStream fin = new BufferedInputStream(new FileInputStream(&amp;quot;Point.class&amp;quot;));&lt;br /&gt;
  ClassFile cf = new ClassFile(new DataInputStream(fin));&lt;br /&gt;
&lt;br /&gt;
A ClassFile object can be written back to a class file. write() in ClassFile writes the contents of the class file to a given DataOutputStream. ClassFile provides addField() and addMethod() for adding a field or a method (note that a constructor is regarded as a method at the bytecode level). It also provides addAttribute() for adding an attribute to the class file.&lt;br /&gt;
&lt;br /&gt;
To examine every bytecode instruction in a method body, CodeIterator is useful. A CodeIterator object allows you to visit every bytecode instruction one by one from the beginning to the end. To otbain this object, do as follows:&lt;br /&gt;
&lt;br /&gt;
     ClassFile cf = ... ;&lt;br /&gt;
     MethodInfo minfo = cf.getMethod(&amp;quot;move&amp;quot;);    // we assume move is not overloaded.&lt;br /&gt;
     CodeAttribute ca = minfo.getCodeAttribute();&lt;br /&gt;
     CodeIterator i = ca.iterator();&lt;br /&gt;
&lt;br /&gt;
Other extensions are being developed to include reflective systems for C++ and Java e.g. OpenC++ and OpenJava which are extensible preprocessors based on compile-time reflection in C++ and Java respectively.&lt;br /&gt;
&lt;br /&gt;
=== JRuby ===&lt;br /&gt;
&lt;br /&gt;
JRuby is a complete implementation of Ruby in Java. The scripting and functional features of the Ruby language can be used by Java developers.[http://depth-first.com/articles/2006/10/24/metaprogramming-with-ruby-mapping-java-packages-onto-ruby-modules] Simple metaprogramming techniques can be  extended from  Ruby so that Java packages are mapped onto to Ruby modules. This would be something like a Ruby-Java Bridge, since JRuby can be run from any platform with a JVM.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
Using JRuby API calling JRuby from Java&lt;br /&gt;
&lt;br /&gt;
    import org.jruby.*;&lt;br /&gt;
    public class SimpleJRubyCall {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
        Ruby runtime = Ruby.getDefaultInstance();&lt;br /&gt;
    runtime.evalScript(“puts 1+2”);&lt;br /&gt;
      }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
With metaprogramming using JRuby one can&lt;br /&gt;
* add methods to class,&lt;br /&gt;
*  add instance methods&lt;br /&gt;
*  add to have Java classes&lt;br /&gt;
&lt;br /&gt;
Since metaprogramming empowers the programmer to create domain specific languages(DSL), the ones created by JRuby can always leverage Java libraries to build wrapper functionalities.&lt;br /&gt;
e.g. Simple JRuby DSL on top of HtmlUnit&lt;br /&gt;
&lt;br /&gt;
=== AspectJ ===&lt;br /&gt;
Another library worth mentioning here is AspectJ. It enforces the aspect oriented programming (AOP) approach in Java. Aspect oriented programming is a complimentary programming paradigm to object oriented programming and is used to improve the modularity of software systems. Thus, while object oriented programming is great for modeling common behavior on a hierarchy of objects, aspect oriented programming allows you to define cross-cutting concerns by adding direct semantics and can be applied across heterogeneous object models. [http://static.springsource.org/spring/docs/2.0.x/reference/aop.html] Applications of aspect oriented programming include logging, instrumenting and debugging. &lt;br /&gt;
&lt;br /&gt;
In object oriented programs, the natural unit of modularity is the class. In AspectJ, aspects modularize concerns that affect more than one class. In addition to classes, aspect oriented programming uses 'aspects'. Aspects enable modularization of crosscutting concerns such as transaction management that cut across multiple types and objects. Thus, AspectJ package achieves metaprogramming features with more controllability.&lt;br /&gt;
&lt;br /&gt;
AspectJ introduces declaring aspects in the statically typed language Java by using 3 key concepts -&lt;br /&gt;
* Join Points - well defined points in program execution&lt;br /&gt;
* Advice - defines additional code to be executed around join points&lt;br /&gt;
* Pointcut - define those points in the source code of a program where an advice will be applied&lt;br /&gt;
&lt;br /&gt;
The core task of AspectJ's advice weaver is to statically transform a program so that at runtime it will behave according to the AspectJ language semantics. The AspectJ weaver takes class files as input and produces class files as output. The weaving process itself can take place at one of three different times: compile-time, post-compile time, and load-time. These two java files are 'woven' together by compiler i.e. the class and the aspect behavior are tied together. This is also known as 'plugging-in' the aspect. [http://oreilly.com/catalog/9780596006549]&lt;br /&gt;
&lt;br /&gt;
Example - Simple tracing/logging&lt;br /&gt;
&lt;br /&gt;
Consider the HelloWorld class below which implements an application that simply displays &amp;quot;Hello World!&amp;quot; on the standard output.&lt;br /&gt;
 package helloworld; &lt;br /&gt;
 class HelloWorld {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
            new HelloWorld().printMessage();&lt;br /&gt;
    }   &lt;br /&gt;
    void printMessage() {&lt;br /&gt;
            System.out.println(&amp;quot;Hello world!&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Consider another Java source file with an aspect definition as follows - &lt;br /&gt;
 package helloworld;&lt;br /&gt;
 aspect Trace of eachobject(instanceof(HelloWorld)) {&lt;br /&gt;
    pointcut printouts(): receptions(void printMessage());&lt;br /&gt;
    before(): printouts() {&lt;br /&gt;
              System.out.println(&amp;quot;*** Entering printMessage ***&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    after():  printouts() {&lt;br /&gt;
              System.out.println(&amp;quot;*** Exiting printMessage ***&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In above example, the Trace aspect injects tracing messages before and after method main of class HelloWorld. If one does not want tracing, one can simply leave the aspect out and plug it in as and when required.&lt;br /&gt;
&lt;br /&gt;
In contrast to reflection[low level], AspectJ provides more carefully controlled power, drawing on the rules learned from object-oriented development to encourage a clean and understandable program structure. An aspect imposes behavior on a class, rather than a class requesting behavior from an aspect. An aspect can modify a class without needing to edit that class - also known as 'reverse inheritance'.&lt;br /&gt;
&lt;br /&gt;
=== MetaJ ===&lt;br /&gt;
&lt;br /&gt;
MetaJ is another package that supports metaprogramming in the Java language. A MetaJ program consists of the Java code with special metaprogramming declarations that will control how the output code is created. It uses templates and reflection. Templates are abstractions that encapsulate a program pattern written by example. Templates are translated to Java classes, so they can be accessed in the metaprogram. Accessing patterns by example inside ordinary Java programs is a major feature of MetaJ programming. [http://www.jucs.org/jucs_10_7/metaj_an_extensible_environment] &lt;br /&gt;
&lt;br /&gt;
Language Dependency:&lt;br /&gt;
MetaJ comprises of a set of concepts that are independent of the base language. These are syntax trees, code references, code iterators and code templates. A framework is defined which in which features common to most languages are abstracted. This supports independence from base language. Thus, generic operations can be defined and components that are language dependent can be plugged onto it. &lt;br /&gt;
&lt;br /&gt;
Execution Flow Representation:&lt;br /&gt;
&lt;br /&gt;
[[Image:Meta_3.jpg]]&lt;br /&gt;
&lt;br /&gt;
Example: &lt;br /&gt;
&lt;br /&gt;
Template :  SampleTempl&lt;br /&gt;
&lt;br /&gt;
 package myTempl; &lt;br /&gt;
 language = Java // base language plug­in&lt;br /&gt;
 template #CompilationUnit SampleTempl{ &lt;br /&gt;
 #[#PackageDeclaration:pck]# &lt;br /&gt;
 #[#ImportDeclarationList:imps]# &lt;br /&gt;
 class SampleTempl { ... } &lt;br /&gt;
 #TypeDeclaration:td &lt;br /&gt;
 } &lt;br /&gt;
&lt;br /&gt;
Instance of Template : Java Code &lt;br /&gt;
&lt;br /&gt;
 package myTempl; &lt;br /&gt;
 import metaj.framework.AbstractTemplate; &lt;br /&gt;
 public class SampleTempl extends AbstractTemplate{ &lt;br /&gt;
 public final Reference imps, td, pck;&lt;br /&gt;
 ... // Implementation of superclass abstract methods&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Java SDK7 has added support for dynamic typing and metaprogramming and includes MetaJ implementation.&lt;br /&gt;
&lt;br /&gt;
=== C++ Template Metaprogramming ===&lt;br /&gt;
&lt;br /&gt;
In C++, [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch2_S24_rm#Template_Metaprogramming static metaprogramming] is implemented with the help of reflection. The most important implementation of reflection in C++ is using the feature of run time type-identification (RTTI) [http://depth-first.com/articles/2006/10/24/metaprogramming-with-ruby-mapping-java-packages-onto-ruby-modules]. RTTI is a system that keeps information about an object's data type in memory at run time. Run-time type information can apply to simple data types, such as integers and characters, or to generic objects. Enabling RTTI in C++ allows the use of dynamic_cast&amp;lt;&amp;gt; operation, the typeid operator or exceptions [http://en.wikipedia.org/wiki/Run-time_type_information].&lt;br /&gt;
&lt;br /&gt;
The template mechanism in C++ allows defining parametrized classes and functions. Templates together with other C++ features constitute a Turing-complete, compile-time sub- language of C++. A Turing-complete language is a language with at least a conditional and a looping construct. C++ can be considered to be a two-level language since a C++ program may contain both static code, which is evaluated at compile time, and dynamic code, which is executed at run time. Template meta-programs are the part of a C++ source that is executed during compilation. A meta-program can access information about types not generally available to ordinary programs [http://lcgapp.cern.ch/project/architecture/ReflectionPaper.pdf].&lt;br /&gt;
&lt;br /&gt;
Given below is an example of how to use templates for writing a common recursive factorial program:&lt;br /&gt;
  template&amp;lt;int count&amp;gt;&lt;br /&gt;
  class FACTOR{&lt;br /&gt;
  public:&lt;br /&gt;
      enum {RESULT = count * FACTOR&amp;lt;count-1&amp;gt;::RESULT};&lt;br /&gt;
       };&lt;br /&gt;
  class FACTOR&amp;lt;1&amp;gt;{&lt;br /&gt;
  public:&lt;br /&gt;
      enum {RESULT = 1};&lt;br /&gt;
       };&lt;br /&gt;
&lt;br /&gt;
If we write this-&lt;br /&gt;
  int j = FACTOR&amp;lt;5&amp;gt;::RESULT;&lt;br /&gt;
&lt;br /&gt;
The above line will calculate the value of 5 factorial. As we instantiate FACTOR&amp;lt;5&amp;gt; the definition of this class depends on FACTOR&amp;lt;4&amp;gt;, which in turn depend on FACTOR&amp;lt;3&amp;gt; and so on. The compiler needs to create all these classes until the template specialization FACTOR&amp;lt;1&amp;gt; is reached. This means the entire recursion is done by the compiler during compile time and it uses the result as if it is a constant.&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Dynamically typed languages are best suited to provide support for metaprogramming due to their inherent nature of easily overcoming distinction between code and data e.g. Lisp provides this feature of interchangeability.  Code and data are both represented in Lisp as lists, so any list can easily be treated as either code or data.  &lt;br /&gt;
It’s simple, therefore, to manipulate code as data, and then execute it – either via EVAL or by returning it as the result of a macro expansion. [3]&lt;br /&gt;
&lt;br /&gt;
Thus, statically typed languages achieve metaprogramming using various techniques and tools to achieve the level of flexibility that dynamic languages provide immanently.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://en.wikipedia.org/wiki/Metaprogramming Metaprogramming]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Type_system Type System]&lt;br /&gt;
*[3]  http://www.slideshare.net/aminbandeali/dynamically-and-statically-typed-languages&lt;br /&gt;
*[4]  http://www.developer.com/java/web/article.php/3504271/Java-Reflection-in-Action.htm&lt;br /&gt;
*[5]  http://www.developer.com/java/other/article.php/3556176/An-Introduction-to-Java-Annotations.htm&lt;br /&gt;
*[6]  http://en.wikipedia.org/wiki/Generic_programming&lt;br /&gt;
*[7]  http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf&lt;br /&gt;
*[8]  http://lcgapp.cern.ch/project/architecture/ReflectionPaper.pdf&lt;br /&gt;
*[9]  http://www.csg.is.titech.ac.jp/~chiba/javassist/&lt;br /&gt;
*[10] http://depth-first.com/articles/2006/10/24/metaprogramming-with-ruby-mapping-java-packages-onto-ruby-modules&lt;br /&gt;
*[11] http://static.springsource.org/spring/docs/2.0.x/reference/aop.html&lt;br /&gt;
*[12] http://oreilly.com/catalog/9780596006549&lt;br /&gt;
*[13] http://www.jucs.org/jucs_10_7/metaj_an_extensible_environment&lt;br /&gt;
*[14] http://depth-first.com/articles/2006/10/24/metaprogramming-with-ruby-mapping-java-packages-onto-ruby-modules&lt;br /&gt;
*[15] http://en.wikipedia.org/wiki/Run-time_type_information&lt;br /&gt;
*[16] http://lcgapp.cern.ch/project/architecture/ReflectionPaper.pdf&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://www.cs.tut.fi/~kk/webstuff/MetaprogrammingCpp.pdf Metaprogramming in C++]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Automatic_programming Automatic/Generative Programming]&lt;br /&gt;
*[http://www.slideshare.net/dogangoko/new-features-of-java7-se-presentation News in the upcoming Java 7]&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch2_S24_rm&amp;diff=36351</id>
		<title>CSC/ECE 517 Fall 2010/ch2 S24 rm</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch2_S24_rm&amp;diff=36351"/>
		<updated>2010-09-29T16:17:12Z</updated>

		<summary type="html">&lt;p&gt;Whiteopal: /* Conclusion */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Metaprogramming in Statically Typed Languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot;I'd rather write programs that write programs than write programs&amp;quot; - Richard Sites''&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Metaprogramming is an inherent feature of dynamically typed languages [e.g. Ruby]. However, achieving metaprogramming in statically typed languages [e.g. Java] becomes complex due to compile time abstraction verification. In this topic, we explore how tools and packages are usedto implement metaprogramming in statically typed languages .&lt;br /&gt;
&lt;br /&gt;
== Metaprogramming ==&lt;br /&gt;
&lt;br /&gt;
Metaprogramming is a programming technique of writing computer programs that write or manipulate other programs or themselves, as data. [http://en.wikipedia.org/wiki/Metaprogramming] In other words, it is a programming technique of writing programs with a higher level of abstraction to make it appear as generative programming.  &lt;br /&gt;
&lt;br /&gt;
Metaprogramming involves two kinds of languages-&lt;br /&gt;
* '''Meta-language''' is the language in which meta-programs, which construct or manipulate other programs, are written. &lt;br /&gt;
* '''Object-language''' is the language of programs being manipulated. &lt;br /&gt;
This makes them ‘meta level programs’ whose problem domain are other ‘base level programs’.&lt;br /&gt;
&lt;br /&gt;
[[Image:Meta_1.jpg]]&lt;br /&gt;
&lt;br /&gt;
The ability of a programming language to be its own metalanguage is called reflection or reflexivity.&lt;br /&gt;
&lt;br /&gt;
Simple example of a metaprogram:&lt;br /&gt;
&amp;lt;br&amp;gt;Let us consider a totally fabricated example for our understanding at very high level. Suppose we need to write a C program that printed the following 500 lines of text with a restriction that the program could not use any kind of loop or goto instruction.&lt;br /&gt;
&lt;br /&gt;
Output expected:&lt;br /&gt;
&lt;br /&gt;
  1 Mississippi&lt;br /&gt;
  2 Mississippi&lt;br /&gt;
  3 Mississippi&lt;br /&gt;
  4 Mississippi&lt;br /&gt;
  ...&lt;br /&gt;
  499 Mississippi&lt;br /&gt;
  500 Mississippi&lt;br /&gt;
&lt;br /&gt;
In C this would be then coded as:&lt;br /&gt;
&lt;br /&gt;
  #include &amp;lt;stdio.h&amp;gt;&lt;br /&gt;
  int main(void) {&lt;br /&gt;
    printf(&amp;quot;1 Mississippi\n&amp;quot;);&lt;br /&gt;
    printf(&amp;quot;2 Mississippi\n&amp;quot;);&lt;br /&gt;
        -&lt;br /&gt;
        -&lt;br /&gt;
        -&lt;br /&gt;
    printf(&amp;quot;499 Mississippi\n&amp;quot;);&lt;br /&gt;
    printf(&amp;quot;500 Mississippi\n&amp;quot;);&lt;br /&gt;
    return 0;&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
With the power of a metaprogramming language we can write another program that writes this program automatically.&lt;br /&gt;
 &lt;br /&gt;
Ruby code:&lt;br /&gt;
&lt;br /&gt;
  File.open('mississippi.c', 'w') do |output|&lt;br /&gt;
   output.puts '#include &amp;lt;stdio.h&amp;gt;'&lt;br /&gt;
   output.puts 'int main(void) {'&lt;br /&gt;
     1.upto(500) do |i|&lt;br /&gt;
       output.puts &amp;quot;    printf(\&amp;quot;#{i} &amp;quot; +&lt;br /&gt;
       &amp;quot;Mississippi\\n\&amp;quot;);&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
   output.puts '    return 0;'&lt;br /&gt;
   output.puts '}'&lt;br /&gt;
  end&lt;br /&gt;
&lt;br /&gt;
This code creates a file called mississippi.c with the expected 500+ lines of C source code.Here, mississippi.c is the generated code and ruby code is the metaprogram.&lt;br /&gt;
&lt;br /&gt;
== Applications of Metaprogramming ==&lt;br /&gt;
&lt;br /&gt;
Metaprogramming is an attractive technique needed when one needs to alter the behavior of a program at run time. Due to its generative nature, it has numerous applications in program development. It can achieve program development without rewriting boiler-plate code [http://en.wikipedia.org/wiki/Boilerplate_text] all the time, ensuring efficiency, increasing modularity and minimizing inconsistent implementation errors. Program generators and program analyzers are the two main categories of meta programs. Metaprograms can be compilers, interpreters, type checkers etc. Some commonly used applications include using a program that outputs source code to - &lt;br /&gt;
* generate sine/cosine/whatever lookup tables&lt;br /&gt;
* to extract a source-form representation of a binary file&lt;br /&gt;
* to compile your bitmaps into fast display routines&lt;br /&gt;
* to extract documentation, initialization/finalization code, description tables, as well as normal code from the same source files&lt;br /&gt;
* to have customized assembly code, generated from a perl/shell/scheme script that does arbitrary processing&lt;br /&gt;
* to propagate data defined at one point only into several cross-referencing tables and code chunks. &lt;br /&gt;
&lt;br /&gt;
Programmers can focus more on the main business logic and new features to be implemented rather than writing repetitive chunks of code (e.g. setups, stubs)[1].&lt;br /&gt;
&lt;br /&gt;
= Typing in Programming Languages =&lt;br /&gt;
&lt;br /&gt;
Earlier programming languages [e.g. Assembly] were written such that each machine level function was reflected in the program code. With advancement in programming languages a certain level of abstraction was reached wherein lower level details were abstracted with one functional unit of work and represented by fewer lines of code e.g. primitive variables are represented with higher level abstract classes. With this abstraction arose a need for checking the validity of operations that could be performed with these abstractions in place.&lt;br /&gt;
&lt;br /&gt;
Typing in programming languages is property of operations and variables in the language that ensure that certain kinds of values that are invalid are not used in operations with each other. Errors related to these are known as type errors. Type checking is the process of verifying and enforcing the constraints of types. Compile time type checking also known as static type checking. Run time type checking is known as dynamic type checking. If a language specification requires its typing rules strongly (i.e., more or less allowing only those automatic type conversions which do not lose information), one can refer to the process as strongly typed, if not, as weakly typed.[http://en.wikipedia.org/wiki/Type_system]&lt;br /&gt;
The above classification can be represented as - &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Image:Meta_2.jpg]]&lt;br /&gt;
&lt;br /&gt;
== Statically Typed Programming Languages ==&lt;br /&gt;
&lt;br /&gt;
Statically typed languages ensure that a fixed type is assigned by the programmer to every variable and parameter. Thus, every expression type can be deduced and type checked during compilation. Static languages try to fix most errors during compile time and strive to minimize failures during run time. Due to this there are many type constraints on the programmer while coding.  At run time, the program uses the classes that it has been given and in this way statically typed languages make distinctions between what happens at compile time and what happens at run time. Examples of statically typed languages are C, C++, Java, C#.&lt;br /&gt;
&lt;br /&gt;
== Dynamically Typed Programming Languages ==&lt;br /&gt;
&lt;br /&gt;
In dynamically typed languages, the variables and parameters do not have a designated type and may take different values at different times. In all the operations, the operands must be type checked at runtime just before performing the operation. Dynamically typed languages don’t need to make a distinction between classes created at compile time and classes provided.  It is possible to define classes at run time and in fact, classes are always defined at run time. These eliminate many developer constraints by avoiding the need of book keeping, declarations etc. Due to this flexibility these languages make an ideal candidate for prototyping and are widely used in agile development environments. However, dynamic languages are known to have performance issues. Static languages have code optimization features at compile time, but dynamic languages allow runtime code optimizations only. [http://www.slideshare.net/aminbandeali/dynamically-and-statically-typed-languages] In dynamically typed languages,  the interpreter deduces type and type conversions, this makes development time faster, but it also can provoke runtime failures. These runtime failures are caught early on during compile time for statically typed languages.&lt;br /&gt;
Examples of dynamically typed languages include Perl, Python,  JavaScript, PHP, Ruby, Groovy.&lt;br /&gt;
&lt;br /&gt;
= Metaprogramming in statically typed languages =&lt;br /&gt;
&lt;br /&gt;
In safety languages [syntactically verbose], metaprogramming is not a standard feature, it can however be achieved. Also, static typing in meta-programs has a number of advantages. In addition to guaranteeing that the meta-program encounters no type-errors while manipulating object-programs, a statically typed metaprogramming language can also guarantee that any of the object-programs generated by the meta-program are also type-correct. A disadvantage of these type system is that (in case of meta-programming languages with weaker type systems) they sometime may be too restrictive in object-programs that the programmer is allowed to construct.&lt;br /&gt;
&lt;br /&gt;
== Techniques and Packages ==&lt;br /&gt;
&lt;br /&gt;
Many language features can be leveraged to achieve some form of characteristics needed to achieve metaprogramming. For instance, languages that support  reflection also allow for dynamic code generation.  e.g. In Microsoft .NET Framework use of &amp;quot;System.Reflection.Emit&amp;quot; namespace is used to generate types and methods at runtime. &lt;br /&gt;
&lt;br /&gt;
=== Reflection ===&lt;br /&gt;
&lt;br /&gt;
Reflection is a valuable language feature to facilitate metaprogramming. Reflection is defined as the ability of a programming language to be its own meta-language. Thus, reflection is writing programs that manipulate other programs or themselves. [http://www.developer.com/java/web/article.php/3504271/Java-Reflection-in-Action.htm] &amp;lt;br&amp;gt;&lt;br /&gt;
e.g. In Java, reflection enables to discover information about the loaded classes:&lt;br /&gt;
* Fields,&lt;br /&gt;
* Methods and constructors&lt;br /&gt;
* Generics information&lt;br /&gt;
* Metadata annotations&lt;br /&gt;
It also enables to use these metaobjects to their instances in run time environment.&lt;br /&gt;
E.g. Method.invoke(Object o, Object… args)&lt;br /&gt;
With the Java reflection API, you can interrogate an object to get all sorts of information about its class. &lt;br /&gt;
&lt;br /&gt;
Consider the following simple example:   &lt;br /&gt;
  public class HelloWorld {&lt;br /&gt;
    public void printName() {&lt;br /&gt;
      System.out.println(this.getClass().getName());&lt;br /&gt;
    }&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
The line&lt;br /&gt;
  (new HelloWorld()).printName();&lt;br /&gt;
sends the string HelloWorld to standard out. Now let x be an instance of HelloWorld or one of its subclasses. The line&lt;br /&gt;
  x.printName();&lt;br /&gt;
sends the string naming the class to standard out.&lt;br /&gt;
&lt;br /&gt;
The printName method examines the object for its class (this.getClass()). In doing so, the decision of what to print is made by delegating to the object's class. The method acts on this decision by printing the returned name. Without being overridden, the printName method behaves differently for each subclass than it does for HelloWorld. The printName method is flexible; it adapts to the class that inherits it, causing the change in behavior.&lt;br /&gt;
&lt;br /&gt;
=== Annotations ===&lt;br /&gt;
&lt;br /&gt;
Annotations are a metaprogramming facility that allow the code to be marked with defined tags. Many APIs require a fair amount of boilerplate code. This boilerplate could be generated automatically by a tool if the program were “decorated” with annotations indicating which methods were remotely accessible. Metadata provided using annotations is beneficial for documentation, compiler checking, and code analysis. One can use this metadata to indicate if methods are dependent on other methods, if they are incomplete, if a certain class must reference another class, and so on. It is used by the compiler to perform some basic compile-time checking. For example there is a override annotation that lets you specify that a method overrides another method from a superclass. At this, the Java compiler will ensure that the behavior you indicate in your metadata actually happens at a code level as well.&lt;br /&gt;
&lt;br /&gt;
An “annotation” has an “annotation type” associated with it which is used for defining it. It is used when you want to create a custom annotation. The type is the actual construct used, and the annotation is the specific usage of that type. An annotation type definition takes an &amp;quot;at&amp;quot; (@) sign, followed by the interface keyword plus the annotation name. On the other hand, an annotation takes the form of an &amp;quot;at&amp;quot; sign (@), followed by the annotation type [http://www.developer.com/java/other/article.php/3556176/An-Introduction-to-Java-Annotations.htm].&lt;br /&gt;
&lt;br /&gt;
Example to Define an Annotation (Annotation type)&lt;br /&gt;
   &lt;br /&gt;
  public @interface MyAnnotation {&lt;br /&gt;
    String doSomething();}&lt;br /&gt;
   Example to Annotate Your Code (Annotation)&lt;br /&gt;
   MyAnnotation (doSomething=&amp;quot;What to do&amp;quot;)&lt;br /&gt;
   public void mymethod() {&lt;br /&gt;
   ....&lt;br /&gt;
   }&lt;br /&gt;
&lt;br /&gt;
==== Annotation Types ====&lt;br /&gt;
There are three annotation types:&lt;br /&gt;
* '''Marker:''' Marker type annotations have no elements, except the annotation name itself.&lt;br /&gt;
Example:&lt;br /&gt;
  public @interface MyAnnotation {&lt;br /&gt;
  } &lt;br /&gt;
Usage:&lt;br /&gt;
  @MyAnnotation&lt;br /&gt;
  public void mymethod() {&lt;br /&gt;
   ....&lt;br /&gt;
  }&lt;br /&gt;
&lt;br /&gt;
* '''Single-Element:''' Single-element, or single-value type, annotations provide a single piece of data only. This can be represented with a data=value pair or, simply with the value (a shortcut syntax) only, within parenthesis.&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
  public @interface MyAnnotation&lt;br /&gt;
  {&lt;br /&gt;
    String doSomething();&lt;br /&gt;
  } &lt;br /&gt;
&lt;br /&gt;
Usage:&lt;br /&gt;
  @MyAnnotation (&amp;quot;What to do&amp;quot;)&lt;br /&gt;
  public void mymethod() {&lt;br /&gt;
   ....&lt;br /&gt;
  } &lt;br /&gt;
&lt;br /&gt;
* '''Full-value or multi-value:''' Full-value type annotations have multiple data members. Therefore, you must use a full data=value parameter syntax for each member.&lt;br /&gt;
Example:&lt;br /&gt;
  public @interface MyAnnotation {&lt;br /&gt;
    String doSomething();&lt;br /&gt;
    int count; String date();&lt;br /&gt;
  } &lt;br /&gt;
Usage:&lt;br /&gt;
  @MyAnnotation (doSomething=&amp;quot;What to do&amp;quot;, count=1,&lt;br /&gt;
              date=&amp;quot;09-09-2005&amp;quot;)&lt;br /&gt;
  public void mymethod() {&lt;br /&gt;
&lt;br /&gt;
=== Generics ===&lt;br /&gt;
&lt;br /&gt;
Generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated  when needed for specific types provided as parameters. [http://en.wikipedia.org/wiki/Generic_programming] Java Generics are primarily a way for library authors to write something once, which users can customize to their own types. They allow the creation of classes and methods that work in the same way on different types of objects. The term &amp;quot;generic&amp;quot; comes from the idea that we'd like to be able to write general algorithms that can be broadly reused for many types of objects rather than having to adapt our code to fit each circumstance.&lt;br /&gt;
&lt;br /&gt;
Generics add a way to specify concrete types to general purpose classes and methods that operated on object before. A Java collection is a flexible data structure that can hold heterogeneous objects where the elements may have any reference type. When you take an element out of a collection, you must cast it to the type of element that is stored in the collection. Generics provides a way for you to communicate the type of a collection to the compiler, so that it can be checked. Once the compiler knows the element type of the collection, the compiler can check that the collection has been used consistently and can insert the correct casts on values being taken out of the collection.[5] Generics are implemented by type erasure: generic type information is present only at compile time, after which it is erased by the compiler. The main advantage of this approach is that it provides total interoperability between generic code and legacy code that uses non-parametrized types (which are technically known as raw types).&lt;br /&gt;
&lt;br /&gt;
Consider a non-generic example:&lt;br /&gt;
   //This program removes 4-letter words from c. Elements must be strings&lt;br /&gt;
   static void expurgate(Collection c)  &lt;br /&gt;
   {    &lt;br /&gt;
        for (Iterator i = c.iterator(); i.hasNext(); )      &lt;br /&gt;
        if (((String) i.next()).length() == 4)        &lt;br /&gt;
        i.remove();&lt;br /&gt;
    }&lt;br /&gt;
Here is the same example modified to use generics:&lt;br /&gt;
   //This program removes the 4-letter words from c&lt;br /&gt;
  static void expurgate(Collection&amp;lt;String&amp;gt; c) &lt;br /&gt;
  {    &lt;br /&gt;
    for (Iterator&amp;lt;String&amp;gt; i = c.iterator(); i.hasNext(); )&lt;br /&gt;
    if (i.next().length() == 4)&lt;br /&gt;
    i.remove();&lt;br /&gt;
  }&lt;br /&gt;
The declaration above reads as “Collection of String c.” Collection is a generic class that takes ‘String’ as its type parameter. The code using generics is clearer and safer. Unsafe cast and a number of extra parentheses have been eliminated. More importantly, we have moved part of the specification of the method from a comment to its signature, so the compiler can verify at compile time that the type constraints are not violated at run time.[http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf]&lt;br /&gt;
&lt;br /&gt;
=== Template Metaprogramming ===&lt;br /&gt;
Template metaprogramming(TMP) or Static Metaprogramming is a technique that allows the execution of programs at compile-time. It uses extremely early binding.&lt;br /&gt;
A primary requirement for a metaprogramming language is providing high-level abstractions to hide the internal representation of base programs.[http://lcgapp.cern.ch/project/architecture/ReflectionPaper.pdf] Each template language is specific for a base language and is generated from it. In this sense, a language of templates is a superset of the base language. Thus templates are abstractions that encapsulate a program pattern written by example.  This concept has been explained in detail in [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch2_S24_rm#C.2B.2B_Template_Metaprogramming section 3.2.5]&lt;br /&gt;
&lt;br /&gt;
Uses of template metaprogramming:&lt;br /&gt;
* Compile-time dimensional analysis&lt;br /&gt;
* Multiple dispatch&lt;br /&gt;
* Design patterns&lt;br /&gt;
* Code optimization &lt;br /&gt;
* Lexing and parsing&lt;br /&gt;
&lt;br /&gt;
== Packages ==&lt;br /&gt;
&lt;br /&gt;
=== Javassist (Java Programming Assistant) ===&lt;br /&gt;
&lt;br /&gt;
Javassist is a Java library providing means to manipulate the Java bytecode of an application. It provides the support for structural reflection, i.e. the ability to change the implementation of a class at runtime. [http://www.csg.is.titech.ac.jp/~chiba/javassist/] Javassist is explicit metaprogramming, in which the metalanguage is Java. It is a load-time reflective system for Java which enables Java programs to define a new class at runtime and to modify a class file when the JVM loads it. Unlike other similar bytecode editors, Javassist provides two levels of API: source level and bytecode level.&lt;br /&gt;
&lt;br /&gt;
If the users use the source-level API, they can edit a class file without knowledge of the specifications of the Java bytecode. They do not have to even write an inserted bytecode sequence; Javassist instead can compile a fragment of source text on line (for example, just a single statement). This ease of use is a unique feature of Javassit against other tools. One can even specify inserted bytecode in the form of source text and Javassist compiles it on the fly. On the other hand, the bytecode-level API allows the users to directly edit a class file as other editors. Thus it makes Java bytecode manipulation simple.&lt;br /&gt;
&lt;br /&gt;
Javassist has the following applications:&lt;br /&gt;
* Aspect Oriented Programming:     Javassist can be a good tool for introducing new methods into a class and for inserting before/after/around advice at the both caller and callee sides.&lt;br /&gt;
* Reflection:     One of applications of Javassist is runtime reflection; Javassist enables Java programs to use a metaobject that controls method calls on base-level objects. No specialized compiler or virtual machine are needed.&lt;br /&gt;
* Remote method invocation:     Another application is remote method invocation. Javassist enables applets to call a method on a remote object running on the web server. Unlike the Java RMI, the programmer does notneed a stub compiler such as rmic; the stub code is dynamically produced by Javassist.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
  BufferedInputStream fin = new BufferedInputStream(new FileInputStream(&amp;quot;Point.class&amp;quot;));&lt;br /&gt;
  ClassFile cf = new ClassFile(new DataInputStream(fin));&lt;br /&gt;
&lt;br /&gt;
A ClassFile object can be written back to a class file. write() in ClassFile writes the contents of the class file to a given DataOutputStream. ClassFile provides addField() and addMethod() for adding a field or a method (note that a constructor is regarded as a method at the bytecode level). It also provides addAttribute() for adding an attribute to the class file.&lt;br /&gt;
&lt;br /&gt;
To examine every bytecode instruction in a method body, CodeIterator is useful. A CodeIterator object allows you to visit every bytecode instruction one by one from the beginning to the end. To otbain this object, do as follows:&lt;br /&gt;
&lt;br /&gt;
     ClassFile cf = ... ;&lt;br /&gt;
     MethodInfo minfo = cf.getMethod(&amp;quot;move&amp;quot;);    // we assume move is not overloaded.&lt;br /&gt;
     CodeAttribute ca = minfo.getCodeAttribute();&lt;br /&gt;
     CodeIterator i = ca.iterator();&lt;br /&gt;
&lt;br /&gt;
Other extensions are being developed to include reflective systems for C++ and Java e.g. OpenC++ and OpenJava which are extensible preprocessors based on compile-time reflection in C++ and Java respectively.&lt;br /&gt;
&lt;br /&gt;
=== JRuby ===&lt;br /&gt;
&lt;br /&gt;
JRuby is a complete implementation of Ruby in Java. The scripting and functional features of the Ruby language can be used by Java developers.[http://depth-first.com/articles/2006/10/24/metaprogramming-with-ruby-mapping-java-packages-onto-ruby-modules] Simple metaprogramming techniques can be  extended from  Ruby so that Java packages are mapped onto to Ruby modules. This would be something like a Ruby-Java Bridge, since JRuby can be run from any platform with a JVM.&lt;br /&gt;
&lt;br /&gt;
Example:&lt;br /&gt;
Using JRuby API calling JRuby from Java&lt;br /&gt;
&lt;br /&gt;
    import org.jruby.*;&lt;br /&gt;
    public class SimpleJRubyCall {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
        Ruby runtime = Ruby.getDefaultInstance();&lt;br /&gt;
    runtime.evalScript(“puts 1+2”);&lt;br /&gt;
      }&lt;br /&gt;
    }&lt;br /&gt;
&lt;br /&gt;
With metaprogramming using JRuby one can&lt;br /&gt;
* add methods to class,&lt;br /&gt;
*  add instance methods&lt;br /&gt;
*  add to have Java classes&lt;br /&gt;
&lt;br /&gt;
Since metaprogramming empowers the programmer to create domain specific languages(DSL), the ones created by JRuby can always leverage Java libraries to build wrapper functionalities.&lt;br /&gt;
e.g. Simple JRuby DSL on top of HtmlUnit&lt;br /&gt;
&lt;br /&gt;
=== AspectJ ===&lt;br /&gt;
Another library worth mentioning here is AspectJ. It enforces the aspect oriented programming (AOP) approach in Java. Aspect oriented programming is a complimentary programming paradigm to object oriented programming and is used to improve the modularity of software systems. Thus, while object oriented programming is great for modeling common behavior on a hierarchy of objects, aspect oriented programming allows you to define cross-cutting concerns by adding direct semantics and can be applied across heterogeneous object models. [http://static.springsource.org/spring/docs/2.0.x/reference/aop.html] Applications of aspect oriented programming include logging, instrumenting and debugging. &lt;br /&gt;
&lt;br /&gt;
In object oriented programs, the natural unit of modularity is the class. In AspectJ, aspects modularize concerns that affect more than one class. In addition to classes, aspect oriented programming uses 'aspects'. Aspects enable modularization of crosscutting concerns such as transaction management that cut across multiple types and objects. Thus, AspectJ package achieves metaprogramming features with more controllability.&lt;br /&gt;
&lt;br /&gt;
AspectJ introduces declaring aspects in the statically typed language Java by using 3 key concepts -&lt;br /&gt;
* Join Points - well defined points in program execution&lt;br /&gt;
* Advice - defines additional code to be executed around join points&lt;br /&gt;
* Pointcut - define those points in the source code of a program where an advice will be applied&lt;br /&gt;
&lt;br /&gt;
The core task of AspectJ's advice weaver is to statically transform a program so that at runtime it will behave according to the AspectJ language semantics. The AspectJ weaver takes class files as input and produces class files as output. The weaving process itself can take place at one of three different times: compile-time, post-compile time, and load-time. These two java files are 'woven' together by compiler i.e. the class and the aspect behavior are tied together. This is also known as 'plugging-in' the aspect. [http://oreilly.com/catalog/9780596006549]&lt;br /&gt;
&lt;br /&gt;
Example - Simple tracing/logging&lt;br /&gt;
&lt;br /&gt;
Consider the HelloWorld class below which implements an application that simply displays &amp;quot;Hello World!&amp;quot; on the standard output.&lt;br /&gt;
 package helloworld; &lt;br /&gt;
 class HelloWorld {&lt;br /&gt;
    public static void main(String[] args) {&lt;br /&gt;
            new HelloWorld().printMessage();&lt;br /&gt;
    }   &lt;br /&gt;
    void printMessage() {&lt;br /&gt;
            System.out.println(&amp;quot;Hello world!&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Consider another Java source file with an aspect definition as follows - &lt;br /&gt;
 package helloworld;&lt;br /&gt;
 aspect Trace of eachobject(instanceof(HelloWorld)) {&lt;br /&gt;
    pointcut printouts(): receptions(void printMessage());&lt;br /&gt;
    before(): printouts() {&lt;br /&gt;
              System.out.println(&amp;quot;*** Entering printMessage ***&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
    after():  printouts() {&lt;br /&gt;
              System.out.println(&amp;quot;*** Exiting printMessage ***&amp;quot;);&lt;br /&gt;
    }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
In above example, the Trace aspect injects tracing messages before and after method main of class HelloWorld. If one does not want tracing, one can simply leave the aspect out and plug it in as and when required.&lt;br /&gt;
&lt;br /&gt;
In contrast to reflection[low level], AspectJ provides more carefully controlled power, drawing on the rules learned from object-oriented development to encourage a clean and understandable program structure. An aspect imposes behavior on a class, rather than a class requesting behavior from an aspect. An aspect can modify a class without needing to edit that class - also known as 'reverse inheritance'.&lt;br /&gt;
&lt;br /&gt;
=== MetaJ ===&lt;br /&gt;
&lt;br /&gt;
MetaJ is another package that supports metaprogramming in the Java language. A MetaJ program consists of the Java code with special metaprogramming declarations that will control how the output code is created. It uses templates and reflection. Templates are abstractions that encapsulate a program pattern written by example. Templates are translated to Java classes, so they can be accessed in the metaprogram. Accessing patterns by example inside ordinary Java programs is a major feature of MetaJ programming. [http://www.jucs.org/jucs_10_7/metaj_an_extensible_environment] &lt;br /&gt;
&lt;br /&gt;
Language Dependency:&lt;br /&gt;
MetaJ comprises of a set of concepts that are independent of the base language. These are syntax trees, code references, code iterators and code templates. A framework is defined which in which features common to most languages are abstracted. This supports independence from base language. Thus, generic operations can be defined and components that are language dependent can be plugged onto it. &lt;br /&gt;
&lt;br /&gt;
Execution Flow Representation:&lt;br /&gt;
&lt;br /&gt;
[[Image:Meta_3.jpg]]&lt;br /&gt;
&lt;br /&gt;
Example: &lt;br /&gt;
&lt;br /&gt;
Template :  SampleTempl&lt;br /&gt;
&lt;br /&gt;
 package myTempl; &lt;br /&gt;
 language = Java // base language plug­in&lt;br /&gt;
 template #CompilationUnit SampleTempl{ &lt;br /&gt;
 #[#PackageDeclaration:pck]# &lt;br /&gt;
 #[#ImportDeclarationList:imps]# &lt;br /&gt;
 class SampleTempl { ... } &lt;br /&gt;
 #TypeDeclaration:td &lt;br /&gt;
 } &lt;br /&gt;
&lt;br /&gt;
Instance of Template : Java Code &lt;br /&gt;
&lt;br /&gt;
 package myTempl; &lt;br /&gt;
 import metaj.framework.AbstractTemplate; &lt;br /&gt;
 public class SampleTempl extends AbstractTemplate{ &lt;br /&gt;
 public final Reference imps, td, pck;&lt;br /&gt;
 ... // Implementation of superclass abstract methods&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
Java SDK7 has added support for dynamic typing and metaprogramming and includes MetaJ implementation.&lt;br /&gt;
&lt;br /&gt;
=== C++ Template Metaprogramming ===&lt;br /&gt;
&lt;br /&gt;
In C++, [http://pg-server.csc.ncsu.edu/mediawiki/index.php/CSC/ECE_517_Fall_2010/ch2_S24_rm#Template_Metaprogramming static metaprogramming] is implemented with the help of reflection. The most important implementation of reflection in C++ is using the feature of run time type-identification (RTTI) [http://depth-first.com/articles/2006/10/24/metaprogramming-with-ruby-mapping-java-packages-onto-ruby-modules]. RTTI is a system that keeps information about an object's data type in memory at run time. Run-time type information can apply to simple data types, such as integers and characters, or to generic objects. Enabling RTTI in C++ allows the use of dynamic_cast&amp;lt;&amp;gt; operation, the typeid operator or exceptions [http://en.wikipedia.org/wiki/Run-time_type_information].&lt;br /&gt;
&lt;br /&gt;
The template mechanism in C++ allows defining parametrized classes and functions. Templates together with other C++ features constitute a Turing-complete, compile-time sub- language of C++. A Turing-complete language is a language with at least a conditional and a looping construct. C++ can be considered to be a two-level language since a C++ program may contain both static code, which is evaluated at compile time, and dynamic code, which is executed at run time. Template meta-programs are the part of a C++ source that is executed during compilation. A meta-program can access information about types not generally available to ordinary programs [http://lcgapp.cern.ch/project/architecture/ReflectionPaper.pdf].&lt;br /&gt;
&lt;br /&gt;
Given below is an example of how to use templates for writing a common recursive factorial program:&lt;br /&gt;
  template&amp;lt;int count&amp;gt;&lt;br /&gt;
  class FACTOR{&lt;br /&gt;
  public:&lt;br /&gt;
      enum {RESULT = count * FACTOR&amp;lt;count-1&amp;gt;::RESULT};&lt;br /&gt;
       };&lt;br /&gt;
  class FACTOR&amp;lt;1&amp;gt;{&lt;br /&gt;
  public:&lt;br /&gt;
      enum {RESULT = 1};&lt;br /&gt;
       };&lt;br /&gt;
&lt;br /&gt;
If we write this-&lt;br /&gt;
  int j = FACTOR&amp;lt;5&amp;gt;::RESULT;&lt;br /&gt;
&lt;br /&gt;
The above line will calculate the value of 5 factorial. As we instantiate FACTOR&amp;lt;5&amp;gt; the definition of this class depends on FACTOR&amp;lt;4&amp;gt;, which in turn depend on FACTOR&amp;lt;3&amp;gt; and so on. The compiler needs to create all these classes until the template specialization FACTOR&amp;lt;1&amp;gt; is reached. This means the entire recursion is done by the compiler during compile time and it uses the result as if it is a constant.&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Dynamically typed languages are best suited to provide support for metaprogramming due to their inherent nature of easily overcoming distinction between code and data e.g. Lisp provides this feature of interchangeability.  Code and data are both represented in Lisp as lists, so any list can easily be treated as either code or data.  &lt;br /&gt;
It’s simple, therefore, to manipulate code as data, and then execute it – either via EVAL or by returning it as the result of a macro expansion. [3]&lt;br /&gt;
&lt;br /&gt;
Thus, statically typed languages achieve metaprogramming using various techniques and tools to achieve the level of flexibility that dynamic languages provide immanently.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  http://en.wikipedia.org/wiki/Metaprogramming&lt;br /&gt;
*[2]  http://en.wikipedia.org/wiki/Type_system&lt;br /&gt;
*[3]  http://www.slideshare.net/aminbandeali/dynamically-and-statically-typed-languages&lt;br /&gt;
*[4]  http://www.developer.com/java/web/article.php/3504271/Java-Reflection-in-Action.htm&lt;br /&gt;
*[5]  http://www.developer.com/java/other/article.php/3556176/An-Introduction-to-Java-Annotations.htm&lt;br /&gt;
*[6]  http://en.wikipedia.org/wiki/Generic_programming&lt;br /&gt;
*[7]  http://www.cs.tut.fi/~kk/webstuff/MetaProgrammingJavaKalvot.pdf&lt;br /&gt;
*[8]  http://lcgapp.cern.ch/project/architecture/ReflectionPaper.pdf&lt;br /&gt;
*[9]  http://www.csg.is.titech.ac.jp/~chiba/javassist/&lt;br /&gt;
*[10] http://depth-first.com/articles/2006/10/24/metaprogramming-with-ruby-mapping-java-packages-onto-ruby-modules&lt;br /&gt;
*[11] http://static.springsource.org/spring/docs/2.0.x/reference/aop.html&lt;br /&gt;
*[12] http://oreilly.com/catalog/9780596006549&lt;br /&gt;
*[13] http://www.jucs.org/jucs_10_7/metaj_an_extensible_environment&lt;br /&gt;
*[14] http://depth-first.com/articles/2006/10/24/metaprogramming-with-ruby-mapping-java-packages-onto-ruby-modules&lt;br /&gt;
*[15] http://en.wikipedia.org/wiki/Run-time_type_information&lt;br /&gt;
*[16] http://lcgapp.cern.ch/project/architecture/ReflectionPaper.pdf&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://www.cs.tut.fi/~kk/webstuff/MetaprogrammingCpp.pdf Metaprogramming in C++]&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Automatic_programming Automatic/Generative Programming]&lt;br /&gt;
*[http://www.slideshare.net/dogangoko/new-features-of-java7-se-presentation News in the upcoming Java 7]&lt;/div&gt;</summary>
		<author><name>Whiteopal</name></author>
	</entry>
</feed>