What are the different types of dependency injection in Spring, and which one is recommended ?
Answer
Spring offers three forms of injection: constructor injection, setter injection, and field injection (with @Autowired directly on the attribute). Constructor injection is recommended, because it makes dependencies explicit and mandatory, allows fields to be declared final, and makes unit testing easier since you can instantiate the class without starting the Spring context. Field injection, while compact, hides dependencies and complicates testing, which is why it's generally discouraged in production code.
Common trap
Many candidates cite field injection as the simplest option without mentioning its downsides for testing and readability, which is a bad signal if the role involves maintainable production code.