Thursday, 30 May 2013

Constructor injection in Spring

                                                       Constructor Dependency Injection


This post will show how to use Constructor dependency injection in Spring IOC. As in the earlier post I already mentioned about the dependency injection and its types. Please refer the below link for more details:-


When container invokes a class constructor having arguments, in which every arguments is representing a dependency on other class is known as constructor dependency injection.

Example of Constructor Dependency injection:-

System Requirements:-
  •          Eclipse Editor or any other.
  •          JDK 1.5 or higher(I am using jdk 1.7.0_03)
  •          Spring jars.


Required Jars are:-

  • spring-core.jar
  • spring-2.5.jar
  • spring-beans.jar
  • spring-context.jar
  • commons-logging.jar
  • dom4j-1.4.jar
  • antlr.jar
  • log4j.jar


Steps for creating Eclipse java project for implementing constructor dependency injection:-
  • Create a java project in eclipse and name it as SpringConstructorInjectionImplementation.
  • Create a package in the src folder with the name as com.spring.gaurav.constructorinjection.example.
  • Create the below files in this package and place the corresponding code in those files.
  • Create an XML file and name it as constructorinjection-beans.xml and place this file in the classpath outside the srcfolder.
  • Execute the ConstructorInjectionClient.java by selecting the option Run as Java Application.


Family.java

package com.spring.gaurav.constructorinjection.example;

public class Family {
            private String husbandName;
            private String wifeName;
            private Kids kids;
           
            public Family(String husbandName, String wifeName, Kids kids){
        this.husbandName = husbandName;
        this.wifeName = wifeName;
        this.kids = kids;
    }

           
            /**
             * @return the husbandName
             */
            public String getHusbandName() {
                        return husbandName;
            }
            /**
             * @param husbandName the husbandName to set
             */
            public void setHusbandName(String husbandName) {
                        this.husbandName = husbandName;
            }
            /**
             * @return the wifeName
             */
            public String getWifeName() {
                        return wifeName;
            }
            /**
             * @param wifeName the wifeName to set
             */
            public void setWifeName(String wifeName) {
                        this.wifeName = wifeName;
            }
            /**
             * @return the kids
             */
            public Kids getKids() {
                        return kids;
            }
            /**
             * @param kids the kids to set
             */
            public void setKids(Kids kids) {
                        this.kids = kids;
            }
}

Kids.java

package com.spring.gaurav.constructorinjection.example;

import java.util.List;

public class Kids {
            private String boyName;
            private String girlName;
            private List<String> otherMembers;
            /**
             * @return the boyName
             */
            public String getBoyName() {
                        return boyName;
            }
            /**
             * @param boyName the boyName to set
             */
            public void setBoyName(String boyName) {
                        this.boyName = boyName;
            }
            /**
             * @return the girlName
             */
            public String getGirlName() {
                        return girlName;
            }
            /**
             * @return the otherMembers
             */
            public List<String> getOtherMembers() {
                        return otherMembers;
            }
            /**
             * @param otherMembers the otherMembers to set
             */
            public void setOtherMembers(List<String> otherMembers) {
                        this.otherMembers = otherMembers;
            }
            /**
             * @param girlName the girlName to set
             */
            public void setGirlName(String girlName) {
                        this.girlName = girlName;
            }
           
           
}

constructorinjection-beans.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-3.0.xsd">

            <bean id="kidsBean" class="com.spring.gaurav.constructorinjection.example.Kids">
                        <property name="boyName">
                                    <value>BIRENDRANATH</value>
                        </property>
                        <property name="girlName">
                                    <value>SAROJINI NAIDU OR SAROJINI CHATTOPADHYAYA - THE NIGHTINGALE OF INDIA</value>
                        </property>
                        <property name="otherMembers">
                                    <list>
                                                <value>BROTHER - HARINDRANATH</value>
                                                <value>HUSBAND - DR. GOVINDARAJULU NAIDU</value>
                                                <value>SON - JAYASURYA</value>
                                                <value>DAUGHTER - PADMAJA</value>
                                                <value>SON - RANDHEER</value>
                                                <value>SON - NILAWAR</value>
                                                <value>SON - LEELAMANI</value>
                                    </list>

                        </property>
            </bean>
            <bean id="familyBean" class="com.spring.gaurav.constructorinjection.example.Family">
                        <constructor-arg index="0" type="java.lang.String"
                                    value="AGORENATH CHATTOPADHYAY" />
                        <constructor-arg index="1" type="java.lang.String"
                                    value="BARADA SUNDARI DEVI" />
                        <constructor-arg index="2">
                                    <ref bean="kidsBean" />
                        </constructor-arg>
            </bean>
</beans>

ConstructorInjectionClient.java

package com.spring.gaurav.constructorinjection.example;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class ConstructorInjectionClient {
            public static void main(String args[]) {
                        ApplicationContext context = new ClassPathXmlApplicationContext(
                                                "constructorinjection-beans.xml");

                        Family family = (Family) context.getBean("familyBean");
                        Kids kids = family.getKids();
                        System.out
                                                .println("*********************************************************************************");
                        System.out
                                                .println("ABOUT SAROJINI NAIDU - FIRST INDIAN WOMAN PRESIDENT OF THE INDIAN NATIONAL CONGRESS");
                        System.out
                                                .println("*********************************************************************************");
                        System.out.println("FATHER NAME IS : " + family.getHusbandName());
                        System.out.println("MOTHER NAME IS : " + family.getWifeName());
                        System.out.println("FIRST BROTHER NAME IS : " + kids.getBoyName());
                        System.out.println("OWN NAME IS : " + kids.getGirlName());
                        List<String> lst = kids.getOtherMembers();
                        System.out.println("\nOTHER FAMILY MEMBER NAMES ARE ");
                        for (String str : lst) {
                                    System.out.println(str);
                        }

            }
}

Project structure:-



Result:-

log4j:WARN No appenders could be found for logger (org.springframework.context.support.ClassPathXmlApplicationContext).
log4j:WARN Please initialize the log4j system properly.
*********************************************************************************
ABOUT SAROJINI NAIDU - FIRST INDIAN WOMAN PRESIDENT OF THE INDIAN NATIONAL CONGRESS
*********************************************************************************
FATHER NAME IS : AGORENATH CHATTOPADHYAY
MOTHER NAME IS : BARADA SUNDARI DEVI
FIRST BROTHER NAME IS : BIRENDRANATH
OWN NAME IS : SAROJINI NAIDU OR SAROJINI CHATTOPADHYAYA - THE NIGHTINGALE OF INDIA

OTHER FAMILY MEMBER NAMES ARE
BROTHER - HARINDRANATH
HUSBAND - DR. GOVINDARAJULU NAIDU
SON - JAYASURYA
DAUGHTER - PADMAJA
SON - RANDHEER
SON - NILAWAR
SON - LEELAMANI

Back to Interview Questions

No comments:

Post a Comment