Pages Navigation Menu

Coding is much easier than you think

Setter injection in Spring – example

 
spring logo
 
Dependency injection in this form, injects the values to attributes inside a class through the setter methods present inside the class. A simple POJO(Plain Old Java Object) has only a set of attributes and the corresponding getters and setters. It is a unit at its simplest which does not implement any other special features. Such POJOs are made abstract parts and the dependency is avoided by setting the values from the underlying Spring framework instead of making the values depend on other units/itself.

 
** UPDATE: Spring Complete tutorial now available here.
 

1. Create the POJO class into which values are to be injected using setter injection

 
File : SimpleSetterInjection
 

package com.simpleCodeStuffs;
public class SimpleSetterInjection {
private String message;
public void setMessage(String message){
this.message = message;
}

public void getMessage(){
System.out.println("Your Message : " + message);
    }
}

 

2. Define the metadata

The value for the attribute of the POJO is provided as <property name=” ” value=” ” /> thereby setting the values of these attributes through the setter method.
 

The values are injected into the POJO by passing the values through setter methods

 
File : Beans.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-3.0.xsd">


<bean id="simpleSetterInjection" class="com.simpleCodeStuffs.SimpleSetterInjection">
<property name="message" value="SimpleCodeStuffs--Simple Setter Injection"/>
</bean>

</beans>

 

Step 3:

Write the main class to place a call to this POJO. The object(POJO) is retrieved by passing a call with getBeans(“beanId”) on the context.
 

File : MainClass.java
 

package com.simpleCodeStuffs;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainClass {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
SimpleSetterInjection obj = (SimpleSetterInjection) context.getBean("simpleSetterInjection");
obj.getMessage();
}

}

 

4. Run it

 
The output appears as

simpleSetterInjectionOutput

 
download
 

About Mohaideen Jamil


Am currently working as a Struts 2 Developer in a reputed IT Organisations. I can help you with teaching Core java and Struts 2. Follow me on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.