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:-

  • Springconfig.xml


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


    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) {
   = 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.


    <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN 2.0//EN"
    <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>

    package com.javarace;
    import org.springframework.beans.factory.BeanFactory;
    import org.springframework.beans.factory.xml.XmlBeanFactory;
    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;
    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