Java Interview Scenario based question:
You're using
@Autowired for field injection in your Spring project. It's simple and it works.
@Component
public class UserService {
@Autowired
private UserRepository userRepository;
}
Your team lead asks you to refactor this as field is injection often discouraged.
Think of below drawbacks of field injection:
βVisibility: Hides a class's required dependencies.
βTestability: Makes unit testing harder, often requiring reflection.
βRuntime Issues: Can lead to NullPointerExceptions if a dependency is missing.
βDesign: Encourages classes with too many responsibilities (violating SRP).
So what's the recommended alternative?
β Constructor Injection.
Dependencies are passed explicitly when the object is created, making them non-negotiable requirements.
@Component
public class UserService {
private final UserRepository userRepo; // Final!
public UserService(UserRepository userRepo) {
this.userRepo = userRepo;
}
Why is Constructor Injection better?
β Explicit: Clearly defines what a class needs to function.
β Guaranteed: The application won't start if a dependency is missing.
β Immutable: final fields are safer and thread-friendly.
β Testable: Easily mock and pass dependencies in tests.
Leads to more robust and maintainable code
ALT @Autowired