Professional Documents
Culture Documents
13 Spring Di Basics Overview
13 Spring Di Basics Overview
Injection
Dependency Injection
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)
www.luv2code.com
Demo Example
• Our Coach already provides daily workouts
FortuneService
www.luv2code.com
Injection Types
• There are many types of injection with Spring
• Constructor Injection
• Setter Injection
www.luv2code.com
Development Process - Constructor Injection
www.luv2code.com
Step 1: Define the dependency interface and class
File: FortuneService.java
File: HappyFortuneService.java
www.luv2code.com
Step 2: Create a constructor in your class for injections
File: BaseballCoach.java
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