Spring idref Attribute : The idref is an attribute used in spring configuration. In spring, idref is used to pass the id or name of a bean as a string to other bean. Before using the idref, ensure that the bean must be defined in configuration with that id or name, otherwise spring will throw exception. The value pass by the idref attribute is always a string.
Example of idref :
ApplicationContext.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"
xmlns:c="http://www.springframework.org/schema/c"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="collegeClass" class="com.evon.example.idrefExample.College">
<property name="collegeName" value="MIT"/>
</bean>
<bean id="student" class="com.evon.example.idrefExample.Student">
<property name="studentName" value="Sumit"/>
<property name="college" ref="collegeClass"/>
<property name="collegeClassName">
<idref bean="collegeClass"/>
</property>
</bean>
</beans>
Student.java
package com.evon.example.idrefExample;
public class Student {
private College college;
private String studentName;
private String collegeClassName;
public College getCollege() {
return college;
}
College.java
package com.evon.example.idrefExample;
public class College {
private String collegeName;
public String getCollegeName() {
return collegeName;
}
public void setCollegeName(String collegeName) {
this.collegeName = collegeName;
}
}
public void setCollege(College college) {
this.college = college;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getCollegeClassName() {
return collegeClassName;
}
public void setCollegeClassName(String collegeClassName) {
this.collegeClassName = collegeClassName;
}
}
Main.java
package com.evon.example.idrefExample;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
public static void main(String[] args){
ApplicationContext context = new ClassPathXmlApplicationContext("ApplicationContext.xml");
Student st=(Student) context.getBean("student");
String idrefValue = st.getCollegeClassName();
System.out.println("Student name :"+st.getStudentName());
System.out.println("idref name :"+idrefValue);
College college=(College) context.getBean(idrefValue);
System.out.println("College name :"+college.getCollegeName());
}
}
Ouptput:
Student name :Sumit
idref name :collegeClass
College name :MIT
0 Comment(s)