The idref in Spring, The idref element in spring framework


 

The idref in Spring, The idref element in spring framework

In this tutorial you will learn about the idref element in spring framework.

In this tutorial you will learn about the idref element in spring framework.

The idref element in spring framework

The idref element allow you to pass the bean id (which is the string value not the reference) of another bean in the container to a <property/> or <constructor-arg/>. In the given example it is clearly shown how pass the bean id to another bean and also display the bean id.

FirstBean.java

package idref.example;

public class FirstBean {

  private String message = null;

  public String getMessage() {
    return message;
  }

  public void setMessage(String message) {
    this.message = message;
  }

}

AnotherBean.java

package idref.example;

public class AnotherBean {
  private String amessage = null;

  public String getAmessage() {
    return amessage;
  }

  public void setAmessage(String amessage) {
    this.amessage = amessage;
  }

  public void display() {
    System.out.println(amessage);
  }
}

IDREFMain.java

package idref.example;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;


public class IDREFMain {
  public static void main(String[] args) {
    BeanFactory beanfactory = new ClassPathXmlApplicationContext(
    "context.xml");
    AnotherBean bean = (AnotherBeanbeanfactory.getBean("another");
    bean.display();
  }
}

context.xml

<bean id="first" class="idref.example.FirstBean">
    <property name="message" value="Spring is simple."/>
</bean>

<bean id="another" class="idref.example.AnotherBean">
    <property name="amessage" >
      <idref bean="first"/>
    </property>
  </bean>

When you run this application it will display output as shown below:

first

Download this example code

Ads