Tuesday, 3 April 2018

Setter injection in Spring

Setter injection is one of the approach to inject dependencies in Spring. We can use <property> element of <bean> tag to set the properties as shown below.

package com.bk.spring.test;

public class CourseBean {

    private String name;
    private String duration;
    private Double fee;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDuration() {
        return duration;
    }

    public void setDuration(String duration) {
        this.duration = duration;
    }

    public Double getFee() {
        return fee;
    }

    public void setFee(Double fee) {
        this.fee = fee;
    }
   
    public void getCourseDetails(){
        System.out.println("Course " + name + " has " + duration + " duration with fee " + fee);
    }

}

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:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
      <bean name="courseBean" class="com.bk.spring.test.CourseBean">
    <property name="name" value="Java"></property>
    <property name="duration" value="90Days"></property>
    <property name="fee" value="2018"></property>
    </bean>
</beans>

Main test class:

package com.bk.spring.test;

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

    public static void main(String a[]) {

        Resource res = new ClassPathResource("applicationContext.xml");
        BeanFactory factory = new XmlBeanFactory(res);  
        CourseBean courseBean = (CourseBean) factory.getBean("courseBean");
        courseBean.getCourseDetails();

    }

}

Output : Course Java has 90Days duration with fee 2018.0

No comments:

Post a Comment