Spring supports three ways to inject a bean's dependencies — constructor, setter, and field injection — each wiring collaborating objects together differently at bean creation time.
Key Points: • Constructor injection passes dependencies as constructor arguments, making them mandatory and allowing the object to be immutable once constructed. • Setter injection uses public setter methods, letting dependencies be set or changed after construction, which suits optional dependencies. • Field injection applies @Autowired directly to a field, which is concise but hides dependencies from the constructor signature and complicates unit testing. • Constructor injection is the generally recommended approach today because it makes required dependencies explicit and supports immutability with final fields. • Since Spring 4.3, a class with a single constructor doesn't even need an explicit @Autowired annotation on it.
Example: A UserService that absolutely needs a UserRepository to function should use constructor injection so it's impossible to construct the service in an invalid, half-wired state.
Code Example:
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
}Interview Tip: A concise interview answer is:
"Spring supports constructor, setter, and field injection. Constructor injection is my default because it makes required dependencies explicit, allows final fields, and is easy to unit test without needing Spring at all — setter and field injection are more useful for optional or rarely-changed dependencies."