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
Advertisement
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

Advertisement

Related Tags for The ref in Spring, Reference Injection:


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.

Posted on: August 11, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com