Home Tutorial Spring Spring3 Ioc Spring Setter Injection

 
 

Spring Setter Injection
Posted on: August 2, 2010 at 12:00 AM
Here in this example you will see another different type of injection known as setter injection

Basic Setter Injection

Here in this example you will see another different type of injection known as setter injection which is the preferred method dependency injection in Spring. The convention of writing the setter method is that start the method name with set and add the method name start with capital character like setMessage or setName.

SetterInjection.java 

package net.roseindia;

public class SetterInjection {
  private String message = null;

  public String getMessage() {
    return message;
  }

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


SetterInjectionTest.java

package net.roseindia;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SetterInjectionTest {
  public static void main(String[] args) {
    BeanFactory beanfactory = new ClassPathXmlApplicationContext(
        "context.xml");
    SetterInjection bean = (SetterInjectionbeanfactory.getBean("message");
    String msg = bean.getMessage();
    System.out.println(msg);
  }
}

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" xmlns:aop="http://www.springframework.org/schema/aop"
  xsi:schemaLocation="http://www.springframework.org/schema/
beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"
>
  <bean id="message" class="net.roseindia.SetterInjection">
    <property name="message" value="Spring is simple." />
  </bean>
</beans>

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

Spring is simple

Download this example code

Related Tags for Spring Setter Injection:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.