Let's see an example for better clarity to inject primitive and string-based values. Here We have three files:-
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) { 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.
<!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>
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
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