Share on Google+Share on Google+

The ref in Spring, Reference Injection

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. 

public class ReferentialBean {
  private String message = null;

  public String getMessage() {
    return message;

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

import org.springframework.beans.factory.BeanFactory;

public class ReferencialBeanTest {
  public static void main(String[] args) {
    BeanFactory beanfactory = new ClassPathXmlApplicationContext(
    ReferentialBean bean = (ReferentialBeanbeanfactory.getBean("message");


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=""

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

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


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

Spring is simple

Download this example code


Posted on: August 11, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.


Advertisement null