Spring BootDependency Injection in Spring Boot
Spring Boot

Dependency Injection in Spring Boot

Learn how Spring manages object creation and wiring through Dependency Injection.

What is Dependency Injection?

Dependency Injection (DI) is a design pattern where an object receives its dependencies from an external source (the Spring IoC container) rather than creating them itself. This promotes loose coupling, testability, and maintainability.

Constructor Injection (Recommended)

The preferred way to inject dependencies:
Java
@Service
public class OrderService {

    private final ProductRepository productRepository;

    // Constructor injection
    public OrderService(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    public List<Product> getAllProducts() {
        return productRepository.findAll();
    }
}

Field Injection with @Autowired

A simpler but less preferred approach:
Java
@Service
public class UserService {

    @Autowired
    private UserRepository userRepository;

    public User findById(Long id) {
        return userRepository.findById(id).orElse(null);
    }
}