Spring Dependency Injection using the setter method

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

IOutputGenerator

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() {
		outputGenerator.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=”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-2.5.xsd”>
<bean id=”OutputHelper”>
<property name=”outputGenerator” ref=”CsvOutputGenerator” />
</bean>
<bean id=”CsvOutputGenerator” />
</beans>

Run it

Load everything, and run it.

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

Output

This is Csv Output Generator