What is Field Injection?
Field Injection means putting the @Autowired annotation directly on top of a private instance variable without constructors or setters.
BadExample.java (Field Injection)
@Service
public class UserService {
@Autowired // Direct field injection - NOT RECOMMENDED!
private UserRepository userRepository;
}
Why Do Senior Developers Avoid Field Injection?
- Cannot make fields
final: The variable can be accidentally mutated or assigned null. - Hides dependencies: As a class grows, having 10 `@Autowired` fields hides code smell (violates Single Responsibility Principle).
- Hard to Unit Test: You cannot test `UserService` in a plain JUnit test without using heavy Reflection or booting Spring.