Dependency Injection by setter method

Let's see an example for better clarity to inject primitive and string-based values. Here We have three files:-

  • Student.java
  • Springconfig.xml
  • TestSpring.java

  • Student.java

    It is a simple class containing three fields regdno, name and address having setters and getters and a method to display these information.

    Example

    package com.javarace;
    public class Student {
        private int regdno;
        private String name;
        private String address;
        public int getRegdno() {
            return regdno;
        }
        public void setRegdno(int regdno) {
            this.regdno = regdno;
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public String getAddress() {
            return address;
        }
        public void setAddress(String address) {
            this.address = address;
        }
        void display() {
            System.out.println(id + " " + name + " " + address);
        }
    }

    We are providing the information into the bean by this file. The property element invokes the setter method. The value subelement of property will assign the specified value.

    Springconfig.xml

    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
    "http://www.springframework.org/dtd/spring-beans-2.0.dtd">
    <beans>
    <beanid="id1" class="com.javarace.Student">
    <property name="regdno" value=101/ </property>
    <property name="name" value="Trilochan Tarai"/> </property>
    <property name="address" value="Bhubaneswar"/> </property>
    </bean>
    </beans>

    SpringTest.java

    package com.javarace;
    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 SpringTest {
        public static void main(String[] args) {
            Resource res = new ClassPathResource("springconfig.xml");
            BeanFactory factory = new XmlBeanFactory(res);
            Object ob = factory.getBean("id1");
            Student s = (Student) ob;
            s.show();
        }
    }
    
    Output
    101 Trilochan Tarai Bhubaneswar

     

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Data Science with Python Training | Projects

SILAN Technology, BBSR
Call to: 0674-2361252

Comment