In this tutorial you will learn about Reference Injection in spring framework.
In this tutorial you will learn about Reference Injection in spring framework.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 {
|
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 = (ReferentialBean) beanfactory.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