Home  >  Spring Core

Example of idref in Spring

By Arvind Rai, March 24, 2013
idref in spring is to pass the id of a bean to another bean. This id must be string. And there must a bean with that name. It ensures at deployment time that bean with that name exists otherwise it will throw error.
In the below example, there is a bean with name vns of the class City. And we are configuring another bean of Student class with name student. Now we will pass an id as vns to the student bean by idref.

app-context.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="vns" class="com.concretepage.City">
    <property name="cityName" value="Varanasi"/> 
  </bean>
  
  <bean id="student" class="com.concretepage.Student">
	  <property name="city" ref="vns"/> 
	  
	  <property name="name">
	    <idref bean="vns"/>
	  </property>
  </bean>
  
 </beans>
 


Student.java
package com.concretepage;

public class Student {
	private City city;
	private String name;
	public City getCity() {
		return city;
	}
	public void setCity(City city) {
		this.city = city;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
 


City.java
package com.concretepage;
public class City     {
	private String cityName;

	public String getCityName() {
		return cityName;
	}

	public void setCityName(String cityName) {
		this.cityName = cityName;
	}
}
 


AppDemo.java
package com.concretepage;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class AppDemo {
    public static void main(String... args) {
            ApplicationContext context = new ClassPathXmlApplicationContext("app-context.xml");
            Student st=(Student) context.getBean("student");
            String cityName=st.getCity().getCityName();
            System.out.println("cityNmae:"+cityName);
    } 
}
 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS


©2019 concretepage.com | Privacy Policy | Contact Us