Spring Dependency
Injection
Dependency Injection
The dependency inversion principle.
The client delegates to calls to another object
the responsibility of providing its
dependencies.
www.luv2code.com
Car Factory
give me a “Car” object Car
Factory
www.luv2code.com
Spring Container Spring
Object
give me a “Coach” object
Factory
My App
configuration
dependencies
(helper objects) BaseballCoach HockeyCoach CricketCoach
dependencies dependencies
(helper objects) (helper objects)
www.luv2code.com
Spring Container
Spring
• Primary functions Object
Factory
• Create and manage objects (Inversion of Control)
• Inject object’s dependencies (Dependency Injection)
www.luv2code.com
Demo Example
• Our Coach already provides daily workouts
• Now will also provide daily fortunes
• New helper: FortuneService
• This is a dependency Coach
FortuneService
www.luv2code.com
Injection Types
• There are many types of injection with Spring
• We will cover the two most common
• Constructor Injection
• Setter Injection
• Will talk about “auto-wiring” in the Annotations section later
www.luv2code.com
Development Process - Constructor Injection
1. Define the dependency interface and class
Step-
By-S
tep
2. Create a constructor in your class for injections
3. Configure the dependency injection in Spring config file
www.luv2code.com
Step 1: Define the dependency interface and class
File: FortuneService.java
public interface FortuneService {
public String getFortune();
File: HappyFortuneService.java
public class HappyFortuneService implements FortuneService {
public String getFortune() {
return "Today is your lucky day!";
}
}
www.luv2code.com
Step 2: Create a constructor in your class for injections
File: BaseballCoach.java
public class BaseballCoach implements Coach {
private FortuneService fortuneService;
public BaseballCoach(FortuneService theFortuneService) {
fortuneService = theFortuneService;
}
...
}
www.luv2code.com
Step 3: Configure the dependency injection in Spring config file
File: applicationContext.xml
<bean id="myFortuneService"
class="com.luv2code.springdemo.HappyFortuneService">
</bean>
<bean id="myCoach"
class="com.luv2code.springdemo.BaseballCoach">
<constructor-arg ref="myFortuneService" />
</bean>
www.luv2code.com
Spring Container Spring
Object
give me a “Coach” object
Factory
My App
configuration
No A
ssem
Requ bly
ired
dependencies
(helper objects) BaseballCoach HockeyCoach CricketCoach
dependencies dependencies
(helper objects) (helper objects)
www.luv2code.com