๐๐ฒ๐ฝ๐ฒ๐ป๐ฑ๐ฒ๐ป๐ฐ๐ ๐๐ป๐ท๐ฒ๐ฐ๐๐ถ๐ผ๐ป ๐ถ๐ป ๐ฆ๐ฝ๐ฟ๐ถ๐ป๐ด ๐๐ผ๐ผ๐
Spring Boot uses Dependency Injection to manage how objects work together.
A dependency is an object another object needs to do its job. In old code, you might create an object inside another class like this:
UserService creates its own UserRepository.
This creates tight coupling. If you change the repository, the service breaks.
Dependency Injection fixes this. An external source provides the object instead of the class creating it.
Spring Boot uses the IoC Container to manage these objects, called beans. You mark classes so Spring knows to manage them:
- @Component: A general Spring bean.
- @Service: A class for business logic.
- @Repository: A class for database work.
- @Controller or @RestController: Classes for web requests.
You use @Autowired to tell Spring to inject a dependency. However, constructor injection is the best practice.
Why use constructor injection:
- It makes code easier to test.
- It improves readability.
- It supports immutability.
- It shows exactly what a class needs to run.
Here is how the process works:
- Spring Boot starts.
- It scans your classes for annotations.
- It creates bean instances.
- It finds and injects the required dependencies.
- The application is ready.
In a standard setup, a request flows through layers: Client Request -> Controller -> Service -> Repository -> Database.
Spring handles the connections between these layers automatically. This makes your code flexible and easy to scale.
Source: https://dev.to/aj_arul/dependency-injection-in-spring-boot-2mhn