0 day streak
java / beginner
Snippet

Constructor-based Dependency Injection

Constructor injection is the recommended way to handle dependencies. It ensures that required fields are final and the bean is fully initialized upon creation.

snippet.java
java
1
2
3
4
5
6
7
8
@Component
public class NotificationManager {
private final EmailService emailService;
public NotificationManager(EmailService emailService) {
this.emailService = emailService;
}
}
spring
Breakdown
1
private final EmailService emailService;
Declares an immutable dependency.
2
public NotificationManager(EmailService emailService)
Spring automatically finds and injects the required bean through the constructor.