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.

7 comments:

Naveen Katiyar said...

Hi,if you are an internet savvy then you don't need to opt for any online courses.you will get enough learning material on several blogs and sites.Courses which are being offered on above link seems sufficient for a beginner,but if you are at a level of intermediate then such courses won't serve your purpose.If you need more help,then feel free to reach me.

Anonymous said...

I have been browsing on-line greater than 3 hours as of late, yet I by no means discovered any interesting article like yours.
It is pretty value sufficient for me. Personally, if all site owners and bloggers
made good content material as you did, the net might be much more helpful than ever before.
Also visit my page ... diets that work fast

Anonymous said...

This is a topic that's near to my heart... Take care! Exactly where are your contact details though?

My weblog: pirater un compte facebook

Anonymous said...

Hi there it's me, I am also visiting this web page daily, this website is truly pleasant and the people are genuinely sharing fastidious thoughts.

My blog post - Candy Crush Saga Hack

Anonymous said...

I'm curious to find out what blog system you're utilizing?
I'm having some minor security problems with my latest website and I would like to find something more safeguarded. Do you have any recommendations?

Also visit my web-site best cellulite treatment

Anonymous said...

I'm not sure why but this weblog is loading very slow for me. Is anyone else having this problem or is it a issue on my end? I'll check back
later and see if the problem still exists.

My web blog ... Code Psn Gratuit [Dailymotion.Com]

Anonymous said...

Thesе are in faсt fantastic idеas in regarding blogging.


Υou havе toucheԁ some pleasant things hеre.


Any waу kеep up wrintіng.


my wеb blоg - organic potting soil