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

packagecom.spring.gaurav.constructorinjection.example;

public classFamily {
            privateString husbandName;
            privateString wifeName;
            privateKids kids;
           
            publicFamily(String husbandName, String wifeName, Kids kids){
        this.husbandName = husbandName;
        this.wifeName = wifeName;
        this.kids = kids;
    }

           
            /**
             * @return the husbandName
             */
            publicString getHusbandName() {
                        returnhusbandName;
            }
            /**
             * @param husbandName the husbandName to set
             */
            publicvoid setHusbandName(String husbandName) {
                        this.husbandName = husbandName;
            }
            /**
             * @return the wifeName
             */
            publicString getWifeName() {
                        returnwifeName;
            }
            /**
             * @param wifeName the wifeName to set
             */
            publicvoid setWifeName(String wifeName) {
                        this.wifeName = wifeName;
            }
            /**
             * @return the kids
             */
            publicKids getKids() {
                        returnkids;
            }
            /**
             * @param kids the kids to set
             */
            publicvoid setKids(Kids kids) {
                        this.kids = kids;
            }
}

Kids.java

packagecom.spring.gaurav.constructorinjection.example;

import java.util.List;

public classKids {
            privateString boyName;
            privateString girlName;
            privateList<String> otherMembers;
            /**
             * @return the boyName
             */
            publicString getBoyName() {
                        returnboyName;
            }
            /**
             * @param boyName the boyName to set
             */
            publicvoid setBoyName(String boyName) {
                        this.boyName = boyName;
            }
            /**
             * @return the girlName
             */
            publicString getGirlName() {
                        returngirlName;
            }
            /**
             * @return the otherMembers
             */
            publicList<String> getOtherMembers() {
                        returnotherMembers;
            }
            /**
             * @param otherMembers the otherMembers to set
             */
            publicvoid setOtherMembers(List<String> otherMembers) {
                        this.otherMembers = otherMembers;
            }
            /**
             * @param girlName the girlName to set
             */
            publicvoid 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

packagecom.spring.gaurav.constructorinjection.example;

import java.util.List;

importorg.springframework.context.ApplicationContext;
importorg.springframework.context.support.ClassPathXmlApplicationContext;

public classConstructorInjectionClient {
            publicstatic 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

Wednesday, 29 May 2013

Setter Injection in Spring

                                                 Setter Dependency Injection

This post will show how to use Setter 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:-



 
In case of setter dependency injection, container calls the setter methods on the bean class after executing a factory method or no-argument constructor for the instantiation of our beans or spring container (IOC container) will inject the dependencies for using the setter methods in a bean class. This is more preferable dependency injection as compare to constructor dependency injection.

Example of Setter 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 setter dependency injection:-
  • Create a java project in eclipse and name it as SpringSetterInjectionImplementation.
  • Create a package in the src folder with the name as com.spring.gauarv.setterinjection.example.
  • Create the below files in this package and place the corresponding code in those files.
  • Create an XML file and name it as setterinjection-beans.xml and place this file in the classpath outside the src folder.
  • Execute the SetterInjectionClient.java by selecting the option Run as Java Application.

CreateProject.java

package com.spring.gauarv.setterinjection.example;

public class CreateProject {
    public CreateProject() {
        System.out.println("INSIDE CREATEPROJECT CLASS CONSTRUCTOR");
    }

    public void createJavaProject() {
        System.out.println("INSIDE CREATEJAVAPROJECT() METHOD");
    }
}

EclipseTool.java

package com.spring.gauarv.setterinjection.example;

public class EclipseTool {
    private CreateProject createProject;

    /**
     * @return the createProject
     */
    public CreateProject getCreateProject() {
        return createProject;
    }

    /**
     * @param createProject
     *            the createProject to set
     */
    public void setCreateProject(CreateProject createProject) {
        this.createProject = createProject;
    }

    public void javaProjectCreation() {
        createProject.createJavaProject();
    }
}

setterinjection-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="eclipseTool" class="com.spring.gauarv.setterinjection.example.EclipseTool">
        <property name="createProject">
            <bean id="createProject"
                class="com.spring.gauarv.setterinjection.example.CreateProject" />
        </property>
    </bean>
</beans>

SetterInjectionClient.java

package com.spring.gauarv.setterinjection.example;

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

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

        EclipseTool eclipseTool = (EclipseTool) context.getBean("eclipseTool");

        eclipseTool.javaProjectCreation();
    }
}

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.

INSIDE CREATEPROJECT CLASS CONSTRUCTOR
INSIDE CREATEJAVAPROJECT() METHOD