Dependency Injection - XML Configuration

Last Updated on: January 11, 2021 pm

Dependency Injection

Dependency = Helper

How Spring Processes the Config File

How Spring processes Config File

Injection Types

Constructor Injection

1. Define the dependency interface and class

Dependency Injection Interface

Dependency Injection Class

2. Create a constructor in your class for injections

Create Constructor

3. Configure the dependency injection in Spring Config File

Set up Config File for DI

Setter Injection

Inject Dependencies by calling setter methods.

1.Create setter methods in your class for injections

Create Setter Method

2. Configure the dependency injection in Spring config file

Config File

SetterDemo

Setter Demo

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
foo.email=test@gmail.com
foo.team=Royal Challenger Bangalore

2. Load Properties File in Spring Config File

Load properties in applicationContext.xml

1
<context:property-placeholder location='classpath:sport.properties'/>

3. Reference values from Properties File

1
2
<property name="emailAddress" value="${foo.email}"/>
<property name="team" value="${foo.team}"/>

Reference: Udemy, Spring & Hibernate for Beginners (including SpringBoot)