Dependency Injection means an object receives its collaborators from the outside (typically via constructor) instead of creating them with new. In Spring the IoC container instantiates beans, wires dependencies, and manages lifecycles, reducing coupling and improving testability.
@Service
class UserService(private val userRepository: UserRepository) {
fun getUser(id: Long): User {
return userRepository.findById(id).orElseThrow()
}
}Expanding on the short answer — what usually matters in practice:
Here’s an additional example (building on the short answer):
@Service
class UserService(private val userRepository: UserRepository) {
fun getUser(id: Long): User {
return userRepository.findById(id).orElseThrow()
}
}