Home Tutorial Spring Spring3 Ioc The ref in Spring, Reference Injection

 
 

The ref in Spring, Reference Injection
Posted on: August 11, 2010 at 12:00 AM
In this tutorial you will learn about Reference Injection in spring framework.

Reference Injection

In the reference injection one bean definition is injected to another. For reference injection you use the constructor-arg or property's ref attribute instead of the value attribute.

In this example, you will see a bean definition is injected to another bean. The first bean definition is the java.lang.String with the id simpleMessage. It is injected into the second bean definition by reference using the property element's ref attribute.

ReferentialBean.java 

public class ReferentialBean {
  private String message = null;

  public String getMessage() {
    return message;
  }

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

ReferencialBeanTest.java

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

public class ReferencialBeanTest {
  public static void main(String[] args) {
    BeanFactory beanfactory = new ClassPathXmlApplicationContext(
        "context.xml");
    ReferentialBean bean = (ReferentialBeanbeanfactory.getBean("message");
    System.out.println(bean.getMessage());
  }
}

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"
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
                           http://www.springframework.org/schema/beans/spring-beans.xsd">

  <bean id="simpleMessage" class="java.lang.String">
    <constructor-arg value="Spring is simple" />
  </bean>

  <bean id="message" class="ReferentialBean">
    <property name="message" ref="simpleMessage" />
  </bean>

</beans>

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

Spring is simple

Download this example code

Related Tags for The ref in Spring, Reference Injection:


Ask Questions?

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.