What is Dependency injection in Springboot ?
What is dependency injection?
Dependency injection (DI) is a design pattern that allows a programmer to remove hard-coded dependencies and make it possible to change them, whether at run-time or compile-time.
Dependency injection is a technique that allows an object to supply its dependencies, rather than having them hard-coded or created within the object itself. This technique is used to manage and organize the relationships between objects in a program and is a key feature of the Spring framework. In this blog post, we will discuss how dependency injection works in Spring Boot.
When developing a Java enterprise application, it is important to keep the codebase maintainable and easy to test. One way to accomplish this is by using the Dependency Injection (DI) design pattern. The Spring framework provides a comprehensive programming and configuration model for modern Java-based enterprise applications and implements DI to manage dependencies between objects in an application.
Spring Boot, a powerful and versatile framework for Java developers, uses the Spring framework’s core container to implement dependency injection. The core container is responsible for managing the dependencies between objects and uses reflection to create objects and wire them together based on the configuration provided in the application.
When a class requires an instance of another class to perform its operations, it declares a member variable of that type and marks it with the @Autowired
annotation. This tells Spring to inject an instance of the required class when creating an instance of the current class. For example:
@Service
public class MyService {@Autowired
private MyDAO myDAO;public void doSomething() {
myDAO.save();
}}
Happy Learning !