0% found this document useful (0 votes)
3 views6 pages

Dependency Injection

Spring Dependency Injection (DI) is a core concept that allows objects to receive their dependencies from an external source, enhancing code reusability, modularity, and testability. It supports various injection methods, including setter and constructor injection, and centralizes dependency management through the Spring IoC container. The document outlines the need for DI, its types, and provides a mini-project example demonstrating its implementation in a Spring application.

Uploaded by

ahmedelnazer30
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views6 pages

Dependency Injection

Spring Dependency Injection (DI) is a core concept that allows objects to receive their dependencies from an external source, enhancing code reusability, modularity, and testability. It supports various injection methods, including setter and constructor injection, and centralizes dependency management through the Spring IoC container. The document outlines the need for DI, its types, and provides a mini-project example demonstrating its implementation in a Spring application.

Uploaded by

ahmedelnazer30
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Dependency Injection

Spring Dependency Injection with mini project Example


Don't forget to follow me:

LinkedIn
X
Spring Dependency Injection (DI) is a fundamental concept in the Spring Framework that
allows objects to receive their dependencies from an external source rather than creating
them internally.

Eliminates the need for classes to create their own dependencies, making code more
reusable and modular.
Supports constructor, setter, and field injection.
Works with XML configuration, annotations, or Java-based configuration.

Why Dependency Injection is Needed


Dependency Injection is necessary because directly creating dependencies inside classes
can lead to several problems:

[Link] Coupling
Classes that create their own dependencies are tightly coupled to specific
implementations.
Changes in one class may break dependent classes.

[Link] Testability
Directly created dependencies make unit testing difficult.
DI allows injecting mock objects for testing individual components.

[Link] Maintainability
Updating or replacing a dependency requires changes in multiple classes.
DI centralizes dependency management in the Spring container, simplifying
maintenance.

[Link] of Flexibility and Reusability


Classes cannot easily switch to alternative implementations of a dependency.
DI allows using interfaces or multiple implementations without modifying the dependent
class.

[Link] Object Management


Spring IoC container handles object creation, configuration, and lifecycle, reducing
boilerplate code and ensuring consistency across the application.

Types of Spring Dependency Injection


There are two primary types of Spring Dependency Injection:

[Link] Dependency Injection (SDI):


Setter DI involves injecting dependencies via setter methods. To configure SDI, the
@Autowired annotation is used along with setter methods and the property is set through
the <property> tag in the bean configuration file.

package [Link];
import [Link];
import [Link];

public class GFG {


// The object of the interface IGeek
private IGeek geek;

// Setter method for property geek with @Autowired annotation


@Autowired
public void setGeek(IGeek geek) {
[Link] = geek;
}
}

Bean Configuration:

<beans xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]

<bean id="GFG" class="[Link]">


<property name="geek" ref="CsvGFG" />
</bean>

<bean id="CsvGFG" class="[Link]" />


<bean id="JsonGFG" class="[Link]" />
</beans>

This injects the CSVGFG bean into the GFG object using the setter method ( setGeek ).

[Link] Dependency Injection (CDI):


Constructor DI involves injecting dependencies through constructors. To configure CDI, the
<constructor-arg> tag is used in the bean configuration file.
package [Link];
import [Link];

public class GFG {


// The object of the interface IGeek
private IGeek geek;

// Constructor to set the CDI


public GFG(IGeek geek) {
[Link] = geek;
}
}

Bean Configuration:

<beans xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]

<bean id="GFG" class="[Link]">


<constructor-arg>
<bean class="[Link]" />
</constructor-arg>
</bean>

<bean id="CsvGFG" class="[Link]" />


<bean id="JsonGFG" class="[Link]" />
</beans>

This injects the CSVGFG bean into the GFG object via the constructor.

Setter Dependency Injection (SDI) vs. Constructor Dependency Injection (CDI)

Setter DI Constructor DI
Creates mutable objects. Dependencies Creates immutable objects. Dependencies
can be modified after creation. can't be modified after creation. All
Dependencies can be injected later. dependencies must be provided at creation.
Requires addition of @Autowired @Autowired annotation is not needed.
annotation.
It results in circular dependencies or It too can have circular dependencies, it just
partial dependencies. fails faster and more explicitly.
Requires framework or manual setter Easier unit testing - can create objects
calls for dependency injection in tests. directly with mock dependencies.
Steps to Create a Spring DI Project

Prerequisites

Java JDK installed (8 or above)


Eclipse IDE or IntelliJ IDEA
Maven (optional, for dependency management)
Spring Framework libraries (or use Maven/Gradle)

Step 1: Create a Java Project

IntelliJ: New Project -> Java -> Add SDK -> Finish

Step 2: Add Spring Dependencies


Add Spring context dependency in [Link] :

<dependency>
<groupId>[Link]</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.30</version>
</dependency>

Step 3: Create Interfaces and Classes

Create interface and classes to define engine behavior and vehicle dependency.

1. Create an interface ([Link])

public interface IEngine {


void start();
}

2. Create implementation class ([Link])

public class ToyotaEngine implements IEngine {


public void start() {
[Link]("Toyota Engine started");
}
}

3. Create dependent class ([Link])

public class Vehicle {


private IEngine engine;

// Constructor for Constructor DI


public Vehicle(IEngine engine) {
[Link] = engine;
}
// Setter for Setter DI
public void setEngine(IEngine engine) {
[Link] = engine;
}

public void drive() {


[Link]();
[Link]("Vehicle is moving");
}
}

Step 4: Configure Spring Beans


Configure Spring beans in XML to enable Dependency Injection for objects.

<beans xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]

<bean id="engine" class="ToyotaEngine"/>

<bean id="vehicleConstructor" class="Vehicle">


<constructor-arg ref="engine"/>
</bean>

<bean id="vehicleSetter" class="Vehicle">


<property name="engine" ref="engine"/>
</bean>
</beans>

Step 5: Write Main Class to Test DI


Load Spring container and retrieve beans to test Dependency Injection.

import [Link];
import [Link];

public class MainApp {


public static void main(String[] args) {
ApplicationContext context = new
ClassPathXmlApplicationContext("[Link]");

Vehicle vehicle1 = (Vehicle) [Link]("vehicleConstructor");


[Link]();

Vehicle vehicle2 = (Vehicle) [Link]("vehicleSetter");


[Link]();
}
}

Step 6: Run the Project

Save all files.


Run [Link] as a Java Application.

Output:

Toyota Engine started


Vehicle is moving
Toyota Engine started
Vehicle is moving

Suggested Quiz

3 Questions

1. Which of the following is NOT a type of dependency injection in Spring?

A. Constructor injection
B. Setter injection
C. Method injection
D. Field injection

2. What does Dependency Injection (DI) help to achieve in Spring?

A. Reduces class dependencies


B. Increases coupling
C. Simplifies data management
D. Automatically handles user authentication

3. What is dependency injection in Spring?

A. Creating objects manually inside classes


B. Managing database connections automatically
C. Providing dependencies to objects instead of creating them
D. Handling HTTP requests

You might also like