The In Spring framework Setter Injection is used to inject the value into the instance variable from the xml file without hard coding into the java fil. For this we create a XML file. In this file we map the bean class and there attributes and specify the default value into it. Some steps are given below to inject the value into the bean property.
At First create the Bean class StudentBean.java as
StudentBean.java
package net.roseindia;
public class StudentBean {
private int roll;
private String name;
private String course;
public int getRoll() {
return roll;
}
public void setRoll(int roll) {
this.roll = roll;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
@Override
public String toString() {
System.out.println("Roll No- " + this.roll);
System.out.println("Name- " + this.name);
System.out.println("Course- " + this.course);
return super.toString();
}
}
StudentBean.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" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="student" class="net.roseindia.StudentBean"> <property name="roll" value="1" /> <property name="name" value="John Trikarson" /> <property name="course" value="M.Tech" /> </bean> </beans>
MainClaz.java
package net.roseindia;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainClaz {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"studentBean.xml");
StudentBean bean = (StudentBean) context.getBean("student");
System.out.println(bean);
}
}
| Roll No- 1 Name- John Trikarson Course- M.Tech |
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.