Spring supports three types of dependency injection: constructor, setter and field injection.
Constructor injection passes dependencies as constructor arguments.
Setter injection calls a setter marked with @Autowired after the object is created.
Field injection puts @Autowired on a field, and Spring sets it through reflection.
// Constructor Injection (Recommended)
@Service
public class UserService {
private final UserRepository userRepository;
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
}
// Field Injection
@Service
public class UserService {
@Autowired
private UserRepository userRepository;
}
Prefer constructor injection. The fields can be final, the object never exists without its dependencies, and a test can pass mocks to the constructor with no container. A class with one constructor needs no @Autowired on it.
Use setter injection for optional dependencies. Avoid field injection, because it hides what a class needs and makes it hard to test without Spring.
Rewriting in plainer words…
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.