This tutorial provides a sample spring program to explain how the dependency injects a bean using the setter method.


An interface and implemntation class of it.

package com.j2eebrain.output;
public interface IOutputGenerator
	public void generateOutput();
package com.j2eebrain.output.impl;
import com.j2eebrain.output.IOutputGenerator;
public class CsvOutputGenerator implements IOutputGenerator {
	public void generateOutput() {
		System.out.println("This is Csv Output Generator");

Helper class

A helper class, later use Spring to DI the IOutputGenerator.

package com.j2eebrain.output;
<pre>import com.j2eebrain.output.IOutputGenerator;
public class OutputHelper {
	IOutputGenerator outputGenerator;
	public void generateOutput() {
	//Dependency Injection using the  setter method
public void setOutputGenerator(IOutputGenerator outputGenerator) {
		this.outputGenerator = outputGenerator;

Spring configuration

Configure bean in Spring configuration file, and reference the bean “CsvOutputGenerator” into “OutputHelper”, via property tag, ref attribute.

In this case, Spring will DI the bean “CsvOutputGenerator” into “OutputHelper” class, via setter method “setOutputGenerator(IOutputGenerator outputGenerator)”.

<beans xmlns=””
<bean id=”OutputHelper”>
<property name=”outputGenerator” ref=”CsvOutputGenerator” />
<bean id=”CsvOutputGenerator” />

Run it

Load everything, and run it.

package com.j2eebrain.common;
import org.springframework.context.ApplicationContext;
import com.j2eebrain.output.OutputHelper;
public class App {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
OutputHelper output = (OutputHelper)context.getBean("OutputHelper");


This is Csv Output Generator

READ  Spring Annotations