Showing posts with label Spring IoC. Show all posts
Showing posts with label Spring IoC. Show all posts

Tuesday, 18 December 2012

Spring IoC Constructor Injection

Posted by Naveen Katiyar On 03:45 7 comments

Spring IoC Constructor Value Injection

Spring IoC Constructor Value Injection is a method of constructor injection in which the value of the attributes of a bean are set using constructor of the class. That means the constructor of the bean must be defined to accept attributes values and set the values to bean properties.
We will see the method of using Spring IoC Constructor Value Injection to set dependencies in Person bean.


Person Bean Code (Person.java)
 package com.naveen.beans;

public class Person {
    private String firstName = null;
    private String lastName = null;

    public Person(String firstName, String lastName){
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public String getName(){
        return firstName + " " + lastName;
    }
}

Here, Person bean has two properties and constructor of Person bean allow to set the value of the properties. So, we can use Spring IoC Constructor Value Injection to inject the value of “firstName” and “lastName” in Person.



Spring IoC Bean Configuration file(spring-servlet.xml)


<?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:context="http://www.springframework.org/schema/context"
 xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.0.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="person" class="com.naveen.beans.Person">
        <constructor-arg name="firstName" value="Rita"/>
        <constructor-arg name="lastName" value="Josap"/>
    </bean>
</beans>

In Spring IoC Bean Configuration file, we have configure Person class as a spring bean. <constructor-arg/> tag is used to set constructor parameter values in Spring IoC container. “name” attribute is used to specify the name of the constructor parameter and “value” attributes says the value to be set on it.

SpringBeanTestRunner class to test the example


package com.naveen.runner;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.naveen.beans.Person;

public class SpringBeanTestRunner {

    public static void main(String[] args) {
        System.out.println("Initialing bean factory");
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-servlet.xml");
        System.out.println("Getting person bean");
        Person person = (Person)beanFactory.getBean("person");
        System.out.println("Person Name is " + person.getName());
    }
}
 


In our example runner class, uses ClassPathXmlApplicationContext to load the Spring IoC configuration file “app-config.xml” and configure the beans specified in the configuration file. BeanFactory instance is used to get the person bean and “getName” method is used to print the name in Person bean instance.

That's it,you can run the application by making the changes in source code of previous tutorials.



Spring IoC Constructor Type Injection

In this tutorial, we will learn how we can provide constructor argument value of a bean using data type of argument. Spring IoC Constructor Type Injection is a method in which we provide dependency data on the basis of data type of the Constructor Type. If more than one argument is present in the Constructor of same data type than Spring IoC Container set the value according to the position of the arguments respectively.
Our following example will show the process of using Spring IoC Constructor Type Injection in practical. In our example, there is Peron class which we will configure as a Spring Bean.


Person Bean Code (Person.java)

package com.naveen.beans;

public class Person {
    private String firstName = null;
    private String lastName = null;
    private int age;

    public Person(String firstName, String lastName, int age){
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public String getPersonDetail(){
        return "Name :" + firstName + " " + lastName +"\nAge : " + age;
    }
}

Person bean contains three properties,”firstName”, “lastName” and “age”, which are set through constructor of Person class.


Spring IoC Bean Configuration file(spring-servlet.xml)


<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="person" class="com.naveen.beans.Person">
        <constructor-arg type="int" value="21"/>
        <constructor-arg type="java.lang.String" value="Rita"/>
        <constructor-arg type="java.lang.String" value="Josap"/>
    </bean>

</beans>

In our Spring IoC bean configuration file, Person class has been configured as a Spring bean. To set the properties of Person bean we have used Spring IoC Constructor Type Injection.

<constructor-arg type=”int” value=”21″/>: <constructor-arg/> tag specifies that the property should be set using class constructor. There are two attributes we have used in this configuration. “type” attribute says the data type of the property and “value” attribute indicates the value of the property. If there are more then one constructor argument with same data type, spring will set the value sequentially.

SpringBeanTestRunner class to test the example


package com.naveen.runner;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.naveen.beans.Person;

public class SpringBeanTestRunner {

    public static void main(String[] args) {
        System.out.println("Initialing bean factory");
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-servlet.xml");
        System.out.println("Getting person bean");
        Person person = (Person)beanFactory.getBean("person");
        System.out.println("Person Detail is " + person.getPersonDetail());
    }
}

SpringBeanTestRunner class helps us to test our example. It first creates BeanFactory instance from ClassPathXmlApplicationContext class which loads our Spring IoC Bean Configuration file and configues Person class as a bean. Then, “getBean” method of BeanFactory is used to get the instance of Person class. It prints details of person bean get from Spring IoC container.


That's it,you can run the application by making the changes in source code of previous tutorials.

Sunday, 16 December 2012

Spring IoC Setter Injection

Posted by Naveen Katiyar On 21:10 1 comment

Spring IoC setter value injection 

We will learn the process of setting property values of a bean using Spring IoC Setter Value Injection. For Spring IoC Setter Value Injection to work the bean class must contain setter of the property present.
In the following example we will consider a Person class which has two properties to construct the name of the person. We will set the property values in Spring IoC Bean Configuration file and the print the name of the person.

Person Bean class (Person.java)


package com.naveen.beans;

public class Person {
    private String firstName = null;
    private String lastName = null;

    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getName(){
        return firstName + " " + lastName;
    }
}

Person class has two properties “firstName” and “lastName ” and their getter and setters.

Spring IoC Bean Configuration file(spring-servlet.xml)

In configuration file Person class has been configured as a Spring IoC Bean as you seen in the previous tutorial.


<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="person" class="com.naveen.beans.Person">
        <property name="firstName" value="Carel"/>
        <property name="lastName" value="Staf"/>
    </bean>

</beans>


 
<property/> tag is used to set the value or reference of a property in bean class. This tag has two attributes here. “name” attribute holds the name of the property in bean. In this case there are two properties in Person bean, “firstName” and “lastName”. The “value” attribute holds the value to be set on the property. Spring IoC container will call property setter methods to set the property value.

You can also do the same thing with following bean configuration:

<bean id="person" class="com.naveen.beans.Person">
  <property name="firstName">
      <value>Carel</value>
  </property>
  <property name="lastName">
      <value>Staf</value>
  </property>
</bean>
 

If you want to set null value to a property, then you can use two way to do it :

Both the value will be set as null.

SpringBeanTestRunner class to test the example

Our SpringBeanTestRunner class contains the code to run the example. The runner class first create BeanFactory instance using our Spring IoC Bean Configuration file (spring-servlet.xml) and then get the instance of person bean to call the method “getName’ in it. 


package com.naveen.runner;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.naveen.beans.Person;

public class SpringBeanTestRunner {

    public static void main(String[] args) {
        System.out.println("Initialing bean factory");
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-servlet.xml");
        System.out.println("Getting person bean");
        Person person = (Person)beanFactory.getBean("person");
        System.out.println("Person name is " + person.getName());
    }
}

That's it.You can run the previous example after making above changes.



Spring IoC Setter Bean Ref Injection 

In this session we will go through an example that will make you understand Spring IoC Setter Bean Ref Injection. Bean ref injection means to to pass reference of one bean to another. So the example will show the method of setting one bean reference to another bean in Spring IoC Bean Setter Injection.
In the following example, there is a Address bean to store address of a person and we will pass the reference of Address bean to Person bean using Spring IoC Setter Bean Ref Injection.

Address bean (Address.java)

Address bean has two properties and getter/setter of the properties to store city and country of a person.


package com.naveen.beans;

    public class Address {
    private String city = null;
    private String country = null;
    public String getCity() {
        return city;
    }
    public void setCity(String city) {
        this.city = city;
    }
    public String getCountry() {
        return country;
    }
    public void setCountry(String country) {
        this.country = country;
    }
    @Override
    public String toString() {
        return "City : " + city + ", Country" + country;
    }
}

Person bean code (Person.java)

Person bean contains three properties “firstName”, “lastname” and “address” and their getter and setter.


package com.naveen.beans;

public class Person {
    private String firstName = null;
    private String lastName = null;
    private Address address = null;

    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public Address getAddress() {
        return address;
    }
    public void setAddress(Address address) {
        this.address = address;
    }
    public String getName(){
        return firstName + " " + lastName;
    }

    public String getPersonDetail(){
        return "Name :" + getName() + "\n" + address.toString();
    }
}

Spring IoC Bean Configuration file(spring-servlet.xml)

We have configure both the beans Address and Person in our Spring IoC Bean Configuration file.


<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <bean id="address" class="com.naveen.beans.Address">
        <property name="city" value="New York"/>
        <property name="country" value="USA"/>
    </bean>
    <bean id="person" class="com.naveen.beans.Person">
        <property name="firstName" value="Carel"/>
        <property name="lastName" value="Staf"/>
        <property name="address" ref="address"/>
    </bean>
</beans>

You can see only one new thing from previous tutorial.
<property name=”address” ref=”address”/> : Here “ref” attribute says to Spring that Spring has to create the instance of address bean and set to the property of person bean.

SpringBeanTestRunner class to test the example

SpringBeanTestRunner class will get Person instance from Spring IoC Container and will call the method “getPersonDetail” method which will show the Name and Address of the person to test the example.


package com.naveen.runner;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.naveen.beans.Person;

public class SpringBeanTestRunner {

    public static void main(String[] args) {
        System.out.println("Initialing bean factory");
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-servlet.xml");
        System.out.println("Getting person bean");
        Person person = (Person)beanFactory.getBean("person");
        System.out.println("Person detail is " + person.getPersonDetail());
    }
}

That's it.You can run the previous example after making above changes. 

Thursday, 13 December 2012

Initializing a Spring IoC Bean

Posted by Naveen Katiyar On 21:37 3 comments

 Using Initialization method to initialize a Spring IoC Bean

With the previous tutorial, you know the process of registering a bean class with Spring IoC container using xml configuration files. In this tutorial we will see how to define an initialization method of bean to Spring IoC, so that Spring IoC container invokes the method after creating instance of the bean to perform some initialization work.

Tools Used:
  • Spring IoC Framework 3.0.3
In our example, we will define an initialization method of our Person class that will initialize the properties name and address of the Person class as value “Unknown”.

 Our Spring IoC Bean class with Initialization method


package com.naveen.domain;

public class Person {
    private String name;
    private String address;

    public void init(){
        this.name = "Unknown";
        this.address = "Unknown";
    }
    public String getAddress() {
        return address;
    }
    public void setAddress(String address) {
        this.address = address;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public String toString() {
        return "Name :" + this.name + " and Address : " + this.address;
    }
}

As you can see, the init() method works as a initialization method for Person bean class to initialize it’s properties with value “Unknown”.

Spring IoC Container configuration file
 
Now, we have to tell Spring IoC about the init() method, so that it can invoke it after creating the instance of  bean.


<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    <bean id="person" class="com.naveen.domain.Person" init-method="init"/>
</beans>

init-metthod attribute of <bean/> tag is used for specifying the initialization method of bean.

Run the example to test the output


package com.naveen.runner;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.naveen.domain.Person;

public class SpringBeanTestRunner {

    public static void main(String[] args) {
        BeanFactory factory = new ClassPathXmlApplicationContext("servlet-config.xml");
        Person person = (Person)factory.getBean("person");
        System.out.println("Person detail is : " + person);
    }
}

Our test runner class will create the instance of BeanFactory using ClassPathXmlApplicationContext and load the configuration file, after that it will get the instance of Person bean from BeanFactory and print the Person bean on console.
While running the example in ellipse, you will get following result, which justify that initialization method has bean called by Spring IoC container.

Download Source code


Getting Started with Spring IoC

Posted by Naveen Katiyar On 02:32 No comments

Configuring Spring Bean and creating Spring Bean instance

This quick start will make you go through the implementations of Spring IoC example and illustrate how to configure your Spring Bean in Spring Configuration file and how to get instance of the bean using Spring IoC container. The example will take a example of Cat class (Cat.java) that will implement Speaks interface (Speaks.java) .


Speaks Interface (Speaks.java)

package com.naveen.beans;

public interface Speaks {
    public void talk();
}

Speaks interface has only one method.


Cat Class (Cat.java)

package com.naveen.beans;

public class Cat implements Speaks {

    public void talk() {
        System.out.println("Miao-miao");
    }
}

Cat class implements Speaks interface and define its own version of talk method.

Spring IoC Bean Configuration File to configure Cat class as a Spring Bean

spring-servlet.xml is our Spring Bean Configuration file that configures Cat class as a Spring IoC bean. 


<?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:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <bean id="cat" class="com.naveen.beans.Cat"/>

</beans>

  • <beans/>: tag is the top level tag for Spring IoC bean configuration file. This tag contains all the beans configurations.
  • <bean/>: tag is used to configure a class as a bean in Spring IoC container. There are two attributes in it, one is “id”,is used to identify a bean in Spring IoC container and also used to get the instance of the bean from Spring IoC container, and the other one is “class”, which defines the fully qualified java class to be configure as a bean.
Runner class (SpringBeanTestRunner.java) of the example

SpringBeanTestRunner class will use Spring IoC to create instance of Cat class and will also invoke talk method in that instance.


package com.naveen.runner;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.naveen.beans.Speaks;

public class SpringBeanTestRunner {

    public static void main(String[] args) {
        System.out.println("Initialing bean factory");
        BeanFactory beanFactory = new ClassPathXmlApplicationContext("spring-servlet.xml");
        System.out.println("Getting cat bean instance");
        Speaks speaks = (Speaks)beanFactory.getBean("cat");
        speaks.talk();
    }
}

ClassPathXmlApplicationContext is used to read our Spring IoC bean configuration file “spring-servlet.xml” from class path and configures all beans. BeanFactory is the class that is used as a factory class of all the bean classes in Spring IoC bean configuration file. BeanFactory is also ClassPathXmlApplicationContext in respective to inheritance. Then we use “getBean” method of BeanFactory to get the bean instance by providing bean id as a parameter.

That's it.You can download  source from bellow links. Import the project in Eclipse and run SpringBeanTestRunner class to test Spring IoC Bean creation technique.

Download Source Code with jars

Click here to download source code

 

Wednesday, 12 December 2012

Introduction to Spring IoC

Posted by Naveen Katiyar On 23:58 1 comment

What is Spring IoC?

Before going through the Spring IoC tutorial, we must know what IoC is and why we use it in real life project development.

IoC or Inversion of Control, is also known as Dependency Injection, is used to create loosely coupled software components. Here, loosely coupled means less dependent software components. Let us illustrate it with an example:

There is a Report class used to generate reports of a bank account and ReportFileWriter is a class that creates a file and writes the report data to the file. Data is provided by the Report class to ReportFileWriter and in response it returns the file instance containing the report. So Report class is dependent on ReportFileWriter class. The dependency graph will be as follow:

Dependency Graph   

In this situation Report class will create an instance of class ReportFileWriter and will call the method “createReport” by passing report data:


ReportFileWriter fw = new ReportFileWriter();
fw.createReport(data);


If you think carefully, in this code we are using tight coupled dependency between Report class and ReportFileWriter class. That means if we want to change the file writer class to PDFReportFileWriter in future we have to change the code of Report class. They are tightly coupled.
IoC solves the problem of tight couple and helps to makes the software component loosely coupled, so that we can maintain our code pretty much easily.

IoC or Inversion of Control is a design pattern that provided instances of a bean or class to another when they needed. That means, we do not have to use new keyword to create instance of dependent class. We will just create a reference of dependent class and IoC pattern will set the instance to the reference when needed.

Now, using IoC Report class will have following code :


ReportFileWriter fw = null;

Public void setFw(ReportFileWriter fw){
    this.fw = fw;
}


IoC container will call setter method to set the instance of ReportFileWriter class. We have to configure the dependency in our classes in IoC configuration file. That will tell the IoC container when and how to inject the dependences.

Creating a better loosely coupled model

In this session we will see how to IoC to create effective loosely coupled components. Consider the previous example of Report class. There is a interface named “ReportWriter” which contains following definition:

public interface ReportWriter {
    public File createReport(ReportData data);
}


Any class implementing ReportWriter interface will be able to create report file of its own format. The report class contains following code:


private ReportWriter reportWriter = null;

public void setReportWriter(ReportWriter rw){
    this.reportWriter = rw;
}

//More Code
reportWriter.createReport(data);
//More Code


Now, we want to provide a facility to generate report in two formats, in PDF and in MS Word. So we will create two classes PDFReportWrite and MSWordReportWriter which will implement the interface ReportWriter. We will configure our IoC container in such a way that when we will need a PDF Report the IoC container will create instance of PDFReportWrite and set to ReportWriter reference of Report class and if we need MS Word format then IoC container will create instance of MSWordReportWriter and set to ReportWriter reference of Report class. No more we have to change the code of Report class to generate a different format report. This is the advantage of IoC design pattern.


Types of Dependency Injection:
There are three ways in which a IoC container can inject dependency class instance to the dependent class:
  1. Setter Injection: In this way, IoC container uses setter of the reference to set the instance of dependency class. Spring IoC provides setter Injection facility. We will learn about it with proper examples in next tutorial.
  2. Constructor Injection: In constructor injection IoC container users construction of dependent class to set the instance of dependency class. We will see example of constructor injection in upcoming tutorials using Spring IoC framework.
  3. Interface Injection: It is more complex process of dependency injection in which interfaces are used to inject the instances. Spring IoC container does not support this type of injection.