Showing posts with label constructor injection. Show all posts
Showing posts with label constructor injection. Show all posts

Monday, October 22, 2012

Reference Injection


So far we have only injected constructor and property values with static values, which is useful if you want to eliminate configuration files. Values can also be injected by reference  one bean definition can be injected into another. To do this, you use the constructor-arg or property's ref attribute instead of the value attribute. The ref
attribute then refers to another bean definition's id.

In the following example, the first bean definition is a java.lang.String with the id spring Message. It is injected into the second bean definition by reference using the property element's ref attribute.

ReferenceSetterMessageTest-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="springMessage" class="java.lang.String">
  <constructor-arg value="Spring is fun." />
</bean>
<bean id="message" class="org.springbyexample.di.xml.SetterMessage">
  <property name="message" ref="springMessage" />
</bean>
</beans>

Basic Constructor Injection


Through the Spring beans XML file you can configure your bean to initialize with an argument for the constructor, and then assign the arguments. Spring essentially “injects” the argument into your bean. This is referred to as constructor injection. The following example passes in the String message using a constructor. The class is the same as the one in Basic Bean Creation except the default message on the message variable has been cleared and is now set to null. A single parameter constructor has been added to set a message.

ConstructorMessage .java

public class ConstructorMessage {
  private String message = null;
  public ConstructorMessage(String message) {
    this.message = message;
  }
  public void setMessage(String message) {
    this.message = message;
  }
  public String getMessage() {
   return message;
  }
}

The constructor-arg element injects a message into the bean using the constructor-arg element's value attribute.

ConstructorMessageTest-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="message" class="org.springbyexample.di.xml.ConstructorMessage">
    <constructor-arg  value="Spring is fun." />
  </bean>
</beans>