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.
File : SimpleSetterInjection
File : Beans.xml
File : MainClass.java
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(); } }