Video in progress
What kinds of Dependency Injection are there, and which one is preferred?
There are three ways: constructor, setter and field. Usually people pick the constructor — the dependency becomes mandatory and the field stays final.
📖 Answer
Through the constructor:
@Service
public class ReportService {
private final UserRepository users;
public ReportService(UserRepository users) { this.users = users; }
}
Through a setter:
@Autowired
public void setMailer(Mailer mailer) { this.mailer = mailer; }
Through a field:
@Autowired
private UserRepository users;
Why the constructor is better:
- the field is
finaland doesn't change afterwards; - the object is never left half-built — you can't create it without its dependency;
- in a test you just write
new ReportService(mockRepo)without Spring; - if the parameter list grows too long, you immediately see the class is doing too much.
A setter is fine for an optional dependency. Field injection is awkward both for writing tests and for reading — don't use it in new code.
Sign up to mark studied questions and save your progress.