Sobes.tech
Junior — Middle

Explain the concept of dependency injection in Spring and how it is implemented

sobes.tech AI

Answer from AI

Dependency Injection (DI) in Spring is a way of managing object dependencies, where the Spring container is responsible for creating and wiring objects, rather than the object itself creating or searching for its dependencies.

Main methods of implementing DI in Spring:

  1. Through constructor — dependencies are passed via constructor parameters.
  2. Through setters — dependencies are set via setter methods.
  3. Through fields annotated with @Autowired — Spring automatically injects the required beans.

Example of injection via annotation:

@Component
public class UserService {
    private final UserRepository userRepository;

    @Autowired
    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }
}

Here, Spring will automatically create an instance of UserRepository and pass it to the UserService constructor. This makes it easy to change dependency implementations, simplifies testing, and increases code modularity.

Explain the concept of dependency injection in Spring… - sobes.tech