Dependency Injection (DI) is a design pattern and a technique used in Java Spring (and other frameworks) to achieve Inversion of Control (IoC). In simple terms, DI is a way to provide the objects that a class depends on (its dependencies) from external sources rather than creating them within the class itself. This helps to achieve loose coupling between classes, making the system more modular and easier to maintain.
In the context of Java Spring, Dependency Injection involves the Spring IoC container managing and injecting the dependencies of your beans at runtime. There are mainly two types of DI in Spring:
public class Car {
private Engine engine;
public void setEngine(Engine engine) {
this.engine = engine;
}
}
Example:
public class Car {
private Engine engine;
public Car(Engine engine) {
this.engine = engine;
}
}
In Spring, the IoC container takes care of managing the beans (objects) and their dependencies. It creates instances of the beans and injects the required dependencies at runtime. The configuration of these beans and their dependencies can be done using XML-based configuration, Java-based configuration, or a combination of both.
Here's a brief example using XML-based configuration:
<!-- applicationContext.xml -->
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-
beans.xsd">
<bean id="engine" class="com.example.Engine"/>
<bean id="car" class="com.example.Car">
<constructor-arg ref="engine"/>
</bean>
</beans>
In this example, the Car bean is configured with a constructor argument referencing the Engine bean.
Dependency Injection is a key concept in achieving modularity, maintainability, and testability in your Java Spring applications. It allows you to focus on implementing the business logic of your classes, while the Spring framework takes care of managing the dependencies.
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc