๐——๐—ฒ๐—ฝ๐—ฒ๐—ป๐—ฑ๐—ฒ๐—ป๐—ฐ๐˜† ๐—œ๐—ป๐—ท๐—ฒ๐—ฐ๐˜๐—ถ๐—ผ๐—ป ๐—ถ๐—ป ๐—ฆ๐—ฝ๐—ฟ๐—ถ๐—ป๐—ด ๐—•๐—ผ๐—ผ๐˜

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:

You use @Autowired to tell Spring to inject a dependency. However, constructor injection is the best practice.

Why use constructor injection:

Here is how the process works:

  1. Spring Boot starts.
  2. It scans your classes for annotations.
  3. It creates bean instances.
  4. It finds and injects the required dependencies.
  5. 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