Main Tutorials

Spring Dependency Injection (DI)

In Spring frameowork, Dependency Injection (DI) design pattern is used to define the object dependencies between each other. It exits in two major types :

  • Setter Injection
  • Constructor Injection

1. Setter Injection

This is the most popular and simple DI method, it will injects the dependency via a setter method.

Example

A helper class with a setter method.


package com.mkyong.output;

import com.mkyong.output.IOutputGenerator;

public class OutputHelper
{
	IOutputGenerator outputGenerator;
	
	public void setOutputGenerator(IOutputGenerator outputGenerator){
		this.outputGenerator = outputGenerator;
	}
	
}

A bean configuration file to declare the beans and set the dependency via setter injection (property tag).


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

You just injects a ‘CsvOutputGenerator’ bean into ‘OutputHelper’ object via a setter method (setOutputGenerator).

2. Constructor Injection

This DI method will injects the dependency via a constructor.

Example

A helper class with a constructor.


package com.mkyong.output;

import com.mkyong.output.IOutputGenerator;

public class OutputHelper
{
	IOutputGenerator outputGenerator;
	
        OutputHelper(IOutputGenerator outputGenerator){
		this.outputGenerator = outputGenerator;
	}
}

A bean configuration file to declare the beans and set the dependency via constructor injection (constructor-arg tag).


<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.mkyong.output.OutputHelper">
		<constructor-arg>
			<bean class="com.mkyong.output.impl.CsvOutputGenerator" />
		</constructor-arg>
	</bean>
	
<bean id="CsvOutputGenerator" class="com.mkyong.output.impl.CsvOutputGenerator" />
<bean id="JsonOutputGenerator" class="com.mkyong.output.impl.JsonOutputGenerator" />
		
</beans>

You just injects a ‘CsvOutputGenerator’ bean into ‘OutputHelper’ object via a constructor.

Setter or Constructor injection?

There are no hard rule set by Spring framework, just use whatever type of DI that suit your project needs. However, due to the simplicity of the setter injection, it’s always selected for most of the scenarios.

Reference

1. http://en.wikipedia.org/wiki/Dependency_injection

About Author

author image
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

Subscribe
Notify of
15 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
infoj
8 years ago

Though this post is a great way to learn about setter and constructor dependency injection but doesn’t put much light on What is dependency injection in Spring?

To know more about what is dependency injection please read this post – http://netjs.blogspot.com/2015/09/what-is-dependency-injection-in-spring.html

Ram
11 years ago

Nice post

Anjali
11 years ago

Hi,

Your tutorials are very useful. It helps me to understand the concepts in short time.
I have a doubt regarding the DI. What about @Resource, @Autowire, @Qualifier, @Configurable annotations? Do they define new ways of Dependency Injection?

shareef
8 years ago

mkyong reference please add this my github for your tutorials i started with spring now … https://github.com/shareefhiasat/mkyong

Nguyen Manh Cuong
9 years ago

Hi,In OutputHelper.java file ,I write this code :

public class OutputHelper {
IOutputGenerator outputGenerator;

OutputHelper(IOutputGenerator outputGenerator)
{
this.outputGenerator = outputGenerator;
}

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

public void setOutputGenerator(IOutputGenerator outputGenerator){
this.outputGenerator = outputGenerator;
}
}

And in Spring-comon.xml ,I define bean as bellow :

It appears error :

“Multiple annotations found at this line:
– No constructor with 0 arguments defined in class
‘OutputHelper’ ”

Please help me explain this error .Thanks

shareef
8 years ago

see this link…….https://mkyong.com/spring/spring-di-via-constructor/ why did you defiend twice ? to the same class

deepa
10 years ago

good for short time

Chris
11 years ago

How do I create a list of beans then inject the list ??
i.e. something like this :-

<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">
 
<List id="Helpers"  class="com.mkyong.output.Helper" >
	<bean id="OutputHelper" >
		<constructor-arg>
			<bean class="com.mkyong.output.impl.CsvOutputGenerator" />
		</constructor-arg>
	</bean>
  	<bean id="inputHelper" >
		<constructor-arg>
			<bean class="com.mkyong.output.impl.CsvIputGenerator" />
		</constructor-arg>
	</bean>
</List>

</beans>

So that in my code i can just instantiate a list of helpers.
(apologies if theres an easy way of doing this, Im a Spring newbie)

Dharmi
11 years ago
Reply to  Chris

you can definetely inject dependency for lists. something like this.

<bean id="helpers" class="com.mkyong.output.Helper">
	<property name="listofHelperObjects">
		<set>
			<ref bean="outputHelper"/>
			<ref bean="inputHelper"/>
		</set>
	</property>
</bean>
saurabh gupta
8 years ago

i want to know ,if we are using dependency injection in that case how to pass form parameters value to application-context. xml… so it can inject the parameter values…

viren patel
8 years ago

Thanks. its a nice post.

Naresh
11 years ago

Its good you studied and putting here to help all of us.we appreciate the work….

hai
11 years ago

Apress – Spring Recipes A Problem Solution Approach – book is good for spring

ananthagowri
11 years ago

im new for spring.i want more basic things about strings.

bob gal
11 years ago

hi …is it possible to add two numbers in spring please tell me….