Monday, October 22, 2012

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>

No comments:

Post a Comment