Dependency Injection - XML Configuration
Last Updated on: January 11, 2021 pm
Dependency Injection
Dependency = Helper
How Spring Processes the Config File
Injection Types
Constructor Injection
1. Define the dependency interface and class
2. Create a constructor in your class for injections
3. Configure the dependency injection in Spring Config File
Setter Injection
Inject Dependencies by calling setter methods.
1.Create setter methods in your class for injections
2. Configure the dependency injection in Spring config file
SetterDemo
Question
For the CricketCoach example with Setter Injection, why do we use the CricketCoach class instead of the Coach interface?
Answer
When you retrieve a bean from the Spring container using the Coach interface:
Coach theCricketCoach = context.getBean("myCricketCoach", Coach.class);
You only have access to the methods defined in the Coach interface: getDailyWorkout and getDailyFortune. Even though the actual implementation has additional methods, you only have visibility to methods that are defined at the Coach interface level.
When you retrieve a bean from the Spring container using the CricketCoach class:
CricketCoach theCricketCoach = context.getBean("myCricketCoach", CricketCoach.class);
You have access to the methods defined in the Coach interface: getDailyWorkout and getDailyFortune.
ALSO, you have access to the additional methods defined in the CricketCoach class: getTeam, setTeam.
Injecting Values from Properties File
1. Create Properties File
Create file sport.properties
1 |
|
2. Load Properties File in Spring Config File
Load properties in applicationContext.xml
1 |
|
3. Reference values from Properties File
1 |
|
Reference: Udemy, Spring & Hibernate for Beginners (including SpringBoot)