Monday 25 April 2016

Constructor Injection using Spring Framework

Now that, we already know how to inject the properties of a Bean using <property="   " value=""> its time to call the constructor and inject the values to constructor argument using spring framework. 

Construtor argument injection for single parameter : 

Consider a simple bean as follows : 

class Employee
{
   int empId;
   Employee(int empId)
   {
    this.empId=empId;
    }
}

In above class the Employee bean consist of a property empId, which we are initializing by using constructor.Spring uses the constructor injection concept to call the parameterized constructor of Employee through configuration file as follows : 

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="emp1"
          class="Employee">
        <constructor-arg value="101" />
    </bean>

</beans>
 
The above configuration file will call the single argument constructor in Employee bean and inject the value 101 into the constructor !!!! 

But life is not so simple always : 
Consider the following example : 

public class Employee 
{
 private String name;
 private String address;
 private int age;
 
 public Employee(String name, String address, int age) {
  this.name = name;
  this.address = address;
  this.age = age;
 }
 
 public Employee(String name, int age, String address) {
  this.name = name;
  this.age = age;
  this.address = address;
 }
 //getter and setter methods
 public String toString(){
  return " name : " +name + "\n address : "
               + address + "\n age : " + age;
 }

}
The bean configuration for above Bean would be :
<!--Spring-Customer.xml-->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 <bean id="EmployeeBean" class="Employee">

  <constructor-arg>
   <value>Amit</value>
  </constructor-arg>
  
  <constructor-arg>
   <value>188</value>
  </constructor-arg>
  
  <constructor-arg>
   <value>28</value>
  </constructor-arg>
        </bean>

</beans>
and when we run the application by loading the bean like : 
Employee emp = (Employee)context.getBean("EmployeeBean");
     System.out.println(emp);
we end up with the output :
 name : Amit
 address : 28
 age : 188
What we are expecting above was the first constructor to be called but the second constructor is getting called. In Spring, the argument type ‘188’ is capable convert to int, so Spring just convert it and take the second constructor, even you assume it should be a String.

Solution
To resolve this we need to always make sure that we sepcify the data types for the argument in the configuration file like :
Markup
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 <bean id="EmployeeBean" class="Employee">
 
  <constructor-arg type="java.lang.String">
   <value>Amit</value>
  </constructor-arg>
  
  <constructor-arg type="java.lang.String">
   <value>188</value>
  </constructor-arg>
  
  <constructor-arg type="int">
   <value>28</value>
  </constructor-arg>
  
 </bean>

</beans>
Run it again, now you get what you expected.
Output

name : Amit
address : 188
age : 28

Saturday 16 April 2016

Dependency Injection for Objects in Spring


Now as we already know how to push up properties in to bean using Spring DI, its now a time to take a next step towards containment using Spring. 

In many real life scenario we need to have the object as a property of bean. For instance, if we are creating Employee object like : 


public class Employee {
int empId;
String empName;
Date dt_of_join;

public int getEmpId() {
return empId;
}

public void setEmpId(int empId) {
this.empId = empId;
}

public String getEmpName() {
return empName;
}

public void setEmpName(String empName) {
this.empName = empName;
}

public Date getDt_of_join() {
return dt_of_join;
}

public void setDt_of_join(Date dt_of_join) {
this.dt_of_join = dt_of_join;
}

}

Here the Employee is dependent on the object of Date. We need to create the object of Date and then insert it into Employee.

public class Date {
     int dd, mm, yy;

     public int getDd() {
          return dd;
     }

     public void setDd(int dd) {
          this.dd = dd;
     }

     public int getMm() {
          return mm;
     }

     public void setMm(int mm) {
          this.mm = mm;
     }

     public int getYy() {
          return yy;
     }

     public void setYy(int yy) {
          this.yy = yy;
     }

}

To achieve this containment concept , spring uses Dependency Injection using bean reference. We can do it by following change in our configuration file 


<beans>
<bean id="id1" class="Date">

<property name="dd" value="10" />
<property name="mm" value="12" />
<property name="yy" value="1982" />

</bean>

<bean id="id2" class="Employee">
<property name="empId" value="10" />
<property name="empName" value="Ajay" />
<property name="dt_of_join" ref="id1" />

</bean>


</beans>

We need to first of create a bean of Date class (id1) which we can inject in Employee bean (id2) by using attribute ref="id1" of property "dt_of_join". 

So one can add any number of beans of Date in xml file and can change the reference of that bean in Employee's property at run time without changing coding of application class/Employee class. 

One more important thing is even though we change the definition of Date class, the Employee class and Main application class file would remain unchanged. :-) 










Thursday 14 April 2016

HelloWorld : Basic example of Spring Framework

Hi Folks !!

After a long time coming back to blog !!! Hope you are still in touch with Spring Framework. For all those who are waiting for the first implementation of Spring .. Here I am !!

We had enough theory earlier about what is dependency injection and why dependency enjoy. Lets make our hands wet with some coding now.

HelloWorld Implementation . 

In this implementation we will learn the property injection using spring framework.

To begin with create a bean, MyBean

public class MyBean {

             private String message;

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

             public void show()
             {
                      System.out.println(message);
             }


}

As you can observer, MyBean has a property message, and setter, getter methods for the same. Normaly we would have gone with constructor arguments to initiate the message like :

MyBean mb=new MyBean("My message"); 

But to implement dependency injection we will be injecting this property through xml.

Create a xml file, config.xml in src folder :

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
"http://www.springframework.org/dtd/spring-beans-2.0.dtd">

<beans>
<bean id="id1" class="MyBean">

<property name="message" value="Welcome to spring" />

</bean>

</beans>

Here object of bean MyBean is referred by bean is "id1". The property tag contains attributes name and values which is used to push the values of properties for "id1".

Create application class to load the object from bean container:

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 MainApp {

          public static void main(String[] args)
          {
                   Resource res = new ClassPathResource("config.xml");
                   BeanFactory factory = new XmlBeanFactory(res);

                   Object o = factory.getBean("id1");
                   MyBean wb = (MyBean)o;

                   wb.show();

          }

}

Thats it guys !! You are ready to execute your first spring application. 

Execute MainApp class and you will get output as : 

Welcome to spring

Jar files required to run this application;
1. spring-2.5.jar
2. common-logging-1.1.jar
3. cgilib-2.2.jar


In my coming post I will explain how to push object through dependency injection and pushing the properties through constructor argument.. 

Keep reading  :-)




Wednesday 6 April 2016

Spring Dependency Injection

Spring Dependency Injection
Spring uses inversion of control the dependencies between objects. Traditional approach before Spring framework was to hard code the dependencies and this creates tightly coupled code and there was no easy way to change that. People used to minimize this tight coupling, by resorting to ” programming to an interface and not to an implementation”, but even with that approach, the actual creation of the dependent object was the responsibility of the calling piece of code. Of course there were custom frameworks being developed by various individuals to create some form of  inversion of control to achieve dependency injection ( DI). Spring changed all that by incorporating dependency injection in a framework.
Lets take example of Employee object 
class Employee
{
int empId;
String empName
}
Here when we wish to create object Employee, the Employee object creation is dependent on values of empId and empName i.e. 
Employee e1=new Employee(1,"Vikas");
These values need to be hard coded in the program as stated earlier. The scenario becomes still tough when we have the concept of containment in class like : 
class Date
{
int dd,mm,yy;
Date(int dd,int mm,int yy)
{
this.dd=dd;
this.mm=mm;
this.yy=yy;
}
}
And
class Employee
{
            Date dt_of_join;
            Int empId;
            String empName;
            Employee(int empId,String empName,Date dt_of_join)
            {
                        this.dt_of_join=dt_of_join;
                        this.empId=empId;
                        this.empName=empName
            }
}

Here Employee object is also dependent on object of Date. So, to create object of Employee, one need to create Date object and then push it into Employee object 

i.e.

Date d1=new Date(10,12,1989);

Employee e1=new Employee(1,"Vikas",d1)

This traditional way of creating and pushing objects is very difficult for maintenance of application. So we are in need of a concept called as DI.

Dependency Injection (DI) – Spring

In Spring framework, Dependency Injection (DI) is used to satisfy the dependencies between objects. It exits in two major types :
  1. Constructor Injection
  2. Setter Injection
Dependency Injection offers atleast the following advantages
  • Loosely couple code
  • Separation of responsibility
  • Configuration and code is separate
In next session we will start with the first program of Spring DI with Setter Injection

Attend Online Java Certification Training and excel your career

Hello Java Developer,  Are you staying at home and worried about your future? Do not waste the time in worrying. International certifi...