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.

    <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

About the Author

Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc