Dependency Injection in Spring Boot — Spring Technical Interview Questions & Answers
Constructor, field and setter injection.
Dependency Injection in Spring Boot
- Dependency Injection means Spring gives a class what it needs, instead of the class creating everything itself.
- Constructor injection: Pass dependencies in the constructor — recommended and easy to test.
- Field injection: @Autowired on a field — short, but harder for unit tests.
- Setter injection: Useful for optional dependencies.
- Benefit: Loose coupling — you can swap implementations and mock in tests.
- Huge classes with many hidden @Autowired fields.
- Prefer constructor injection; say why (explicit, final, testable).
Technical Interview Tip: Recommend constructor injection and give one reason.
Code Examples for Dependency Injection in Spring Boot
Dependency Injection in Spring Boot — working example
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@Service
class GreetingService {
String greet(String name) {
return "Hello, " + name;
}
}
@RestController
@RequiredArgsConstructor // constructor injection of final fields
class GreetingController {
private final GreetingService greetings;
@GetMapping("/greet")
String greet() {
return greetings.greet("Spring");
}
}
// Without Lombok — same idea:
// GreetingController(GreetingService greetings) { this.greetings = greetings; }Dependency Injection in Spring Boot — spring injects beans; prefer constructor injection (@RequiredArgsConstructor or explicit ctor) over field @Autowired.
How to Explain Dependency Injection in Spring Boot to an Interviewer
What is Dependency Injection (sb)?
Used for a short Dependency Injection sb example a small REST app Not just the heading
Give one small example of Dependency Injection (sb).
the smallest Dependency Injection sb example you can type Constructor, field and setter injection
What mistake do beginners make with Dependency Injection (sb)?
only saying “Dependency Injection sb” with no example Show the fix
Where do you use Dependency Injection (sb)?
a small REST app a short Dependency Injection sb example