A simple Spring example to show you how to dependency inject a bean via setter method, the most common used DI method.

1. IOutputGenerator

An interface and implemntation class of it.

package com.favtuts.output;
 
public interface IOutputGenerator
{
	public void generateOutput();
}
package com.favtuts.output.impl;

import com.favtuts.output.IOutputGenerator;

public class CsvOutputGenerator implements IOutputGenerator {
	public void generateOutput() {
		System.out.println("This is Csv Output Generator");
	}
}

2. Helper class

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

package com.favtuts.output;

import com.favtuts.output.IOutputGenerator;

public class OutputHelper {
	IOutputGenerator outputGenerator;

	public void generateOutput() {
		outputGenerator.generateOutput();
	}

	//DI via setter method
	public void setOutputGenerator(IOutputGenerator outputGenerator) {
		this.outputGenerator = outputGenerator;
	}
}

3. 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" class="com.favtuts.output.OutputHelper">
		<property name="outputGenerator" ref="CsvOutputGenerator" />
	</bean>
 
	<bean id="CsvOutputGenerator" class="com.favtuts.output.impl.CsvOutputGenerator" />

</beans>

4. Run it

Load everything, and run it.

package com.tuts.heomi.netmon;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.favtuts.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

Download Source Code

$ git clone https://github.com/favtuts/java-spring-tutorials.git
$ cd SpringDISetterMethod

Reference Articles

Leave a Reply

Your email address will not be published. Required fields are marked *