Wednesday, 26 October 2016

Java Source World: Spring Framework-Dependency Injection by Constructor with Example

Spring Framework-Dependency Injection by Constructor with Example


                                                          Java Source World                         A Java quick reference blog




Spring Framework: Dependency Injection by Constructor with Example



Injecting primitive and string-based values


We can inject the dependency by constructor. The <constructor-arg> subelement of <bean> is used for constructor injection. Here we are going to inject

1.    primitive and String-based values
2.    Dependent object (contained object)
3.    Collection values etc.

Injecting primitive and string-based values

Let's see the simple example to inject primitive and string-based values. We have created three files here:

    Employee.java
    applicationContext.xml
    Test.java

Employee.java

It is a simple class containing two fields id and name. There are four constructors and one method in this class.

    package com.springexample; 
     
    public class Employee { 
    private int id; 
    private String name; 
     
    public Employee() {System.out.println("def cons");} 
     
    public Employee(int id) {this.id = id;} 
     
    public Employee(String name) {  this.name = name;} 
     
    public Employee(int id, String name) { 
        this.id = id; 
        this.name = name; 
    } 
     
    void show(){ 
        System.out.println(id+" "+name); 
        
    } 

applicationContext.xml

We are providing the information into the bean by this file. The constructor-arg element invokes the constructor. In such case, parameterized constructor of int type will be invoked. The value attribute of constructor-arg element will assign the specified value. The type attribute specifies that int parameter constructor will be invoked.
  

 <?xml version="1.0" encoding="UTF-8"?> 
    <beans 
        xmlns="http://www.springframework.org/schema/beans" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns:p="http://www.springframework.org/schema/p" 
        xsi:schemaLocation="http://www.springframework.org/schema/beans 
                    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 
    <bean id="e" class="com.springexample.Employee"> 
    <constructor-arg value="10" type="int"></constructor-arg> 
    </bean>     
    </beans> 

Test.java

This class gets the bean from the applicationContext.xml file and calls the show method.

    package com.springexample; 
     
    import org.springframework.beans.factory.BeanFactory; 
    import org.springframework.beans.factory.xml.XmlBeanFactory; 
    import org.springframework.core.io.*; 
     
    public class Test { 
        public static void main(String[] args) { 

             
            Resource r=new ClassPathResource("applicationContext.xml"); 
            BeanFactory factory=new XmlBeanFactory(r); 
             
            Employee s=(Employee)factory.getBean("e"); 
            s.show(); 
             
        } 
    } 

Output:10 null


Injecting string-based values

If you don't specify the type attribute in the constructor-arg element, by default string type constructor will be invoked.

    .... 
    <bean id="e" class="com.springexample.Employee"> 
    <constructor-arg value="10"></constructor-arg> 
    </bean> 
    .... 

If you change the bean element as given above, string parameter constructor will be invoked and the output will be 0 10.

Output:0 10

You may also pass the string literal as following:

    .... 
    <bean id="e" class="com.springexample.Employee"> 
    <constructor-arg value="Sonoo"></constructor-arg> 
    </bean> 
    .... 

Output:0 Sonoo

You may pass integer literal and string both as following

    .... 
    <bean id="e" class="com.springexample.Employee"> 
    <constructor-arg value="10" type="int" ></constructor-arg> 
    <constructor-arg value="Sonoo"></constructor-arg> 
    </bean> 
    .... 

Output:10 Sonoo  

Continue Reading: Constructor Injection with Collection Example



 

                                                          Java Source World                         A Java quick reference blog

Read More »

Java Source World: Spring Framework- Dependency Injection in Spring

Spring Framework- Dependency Injection in Spring






Spring Framework: Dependency Injection in Spring



Dependency Injection (DI) is a design pattern that removes the dependency from the programming code so that it can be easy to manage and test the application. Dependency Injection makes our programming code loosely coupled. To understand the DI better, Let's understand the Dependency Lookup (DL) first:

Dependency Lookup

The Dependency Lookup is an approach where we get the resource after demand. There can be various ways to get the resource for example:

    A obj = new AImpl(); 

In such way, we get the resource(instance of A class) directly by new keyword. Another way is factory method:

    A obj = A.getA(); 

This way, we get the resource (instance of A class) by calling the static factory method getA().

Alternatively, we can get the resource by JNDI (Java Naming Directory Interface) as:

    Context ctx = new InitialContext(); 
    Context environmentCtx = (Context) ctx.lookup("java:comp/env"); 
    A obj = (A)environmentCtx.lookup("A"); 

There can be various ways to get the resource to obtain the resource. Let's see the problem in this approach.

Problems of Dependency Lookup:

There are mainly two problems of dependency lookup.

1.    Tight coupling.  The dependency lookup approach makes the code tightly coupled. If resource is changed, we need to perform a lot of modification in the code.
2.    Not easy for testing. This approach creates a lot of problems while testing the application especially in black box testing.

Dependency Injection:

The Dependency Injection is a design pattern that removes the dependency of the programs. In such case we provide the information from the external source such as XML file. It makes our code loosely coupled and easier for testing. In such case we write the code as:

    class Employee{ 
    Address address; 
     
    Employee(Address address){ 
    this.address=address; 
    } 
    public void setAddress(Address address){ 
    this.address=address; 
         
    } 

In such case, instance of Address class is provided by external souce such as XML file either by constructor or setter method.
Two ways to perform Dependency Injection in Spring framework

Spring framework provides two ways to inject dependency

1.    By Constructor
2.    By Setter method 



 

                                                        Java Source World                         A Java quick reference blog

Read More »

Java Source World: Spring Framework - Setter Injection with Collection Example





Spring Framework: Setter Injection with Collection Example




We can inject collection values by setter method in spring framework. There can be used three elements inside the property element.
It can be:
  1. list
  2. set
  3. map
Each collection can have string based and non-string based values.
In this example, we are taking the example of Forum where One question can have multiple answers. There are three pages:
  1.     Question.java
  2.     applicationContext.xml
  3.     Test.java
In this example, we are using list that can have duplicate elements, you may use set that have only unique elements. But, you need to change list to set in the applicationContext.xml file and List to Set in the Question.java file.
Question.java
This class contains three properties with setters and getters and displayInfo() method that prints the information. Here, we are using List to contain the multiple answers.

    package com.springexample; 
    import java.util.Iterator; 
    import java.util.List; 
     
    public class Question { 
    private int id; 
    private String name; 
    private List<String> answers; 
     
    //setters and getters 
     
    public void displayInfo(){ 
        System.out.println(id+" "+name); 
        System.out.println("answers are:"); 
        Iterator<String> itr=answers.iterator(); 
        while(itr.hasNext()){ 
            System.out.println(itr.next()); 
        } 
    }       
    }  

applicationContext.xml

The list element of constructor-arg is used here to define the list.
    <?xml version="1.0" encoding="UTF-8"?> 
    <beans 
        xmlns="http://www.springframework.org/schema/beans" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xmlns:p="http://www.springframework.org/schema/p" 
        xsi:schemaLocation="http://www.springframework.org/schema/beans  
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 
     
    <bean id="q" class="com.springexample.Question"> 
    <property name="id" value="1"></property> 
    <property name="name" value="What is Java?"></property> 
    <property name="answers"> 
    <list> 
    <value>Java is a programming language</value> 
    <value>Java is a platform</value> 
    <value>Java is an Island</value> 
    </list> 
    </property> 
    </bean>      
    </beans>  

Test.java

This class gets the bean from the applicationContext.xml file and calls the displayInfo method.

    package com.springexample; 
     
    import org.springframework.beans.factory.BeanFactory; 
    import org.springframework.beans.factory.xml.XmlBeanFactory; 
    import org.springframework.core.io.ClassPathResource; 
    import org.springframework.core.io.Resource; 
     
    public class Test { 
    public static void main(String[] args) { 
        Resource r=new ClassPathResource("applicationContext.xml"); 
        BeanFactory factory=new XmlBeanFactory(r); 
         
        Question q=(Question)factory.getBean("q"); 
        q.displayInfo(); 
         
    } 
    }
Also Read:  Spring Framework: Constructor Injection with collection


                                                          Java Source World                         A Java quick reference blog


Read More »