0
0
Spring Bootframework~30 mins

Field injection and why to avoid it in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Field Injection and Why to Avoid It in Spring Boot
📖 Scenario: You are building a simple Spring Boot service that sends notifications. You want to learn how to inject dependencies properly and understand why field injection is discouraged.
🎯 Goal: Create a Spring Boot service class that uses constructor injection instead of field injection to get a NotificationSender bean.
📋 What You'll Learn
Create a NotificationSender interface with a method send(String message).
Create a class EmailNotificationSender that implements NotificationSender.
Create a service class NotificationService that uses constructor injection to get NotificationSender.
Avoid using field injection (@Autowired on fields).
💡 Why This Matters
🌍 Real World
In real Spring Boot applications, managing dependencies clearly helps maintain and test code effectively.
💼 Career
Understanding dependency injection patterns is essential for writing clean, testable, and maintainable Spring Boot applications.
Progress0 / 4 steps
1
Create NotificationSender interface and EmailNotificationSender class
Create an interface called NotificationSender with a method void send(String message). Then create a class called EmailNotificationSender that implements NotificationSender and overrides the send method with an empty body.
Spring Boot
Need a hint?

Use public interface NotificationSender and public class EmailNotificationSender implements NotificationSender. Annotate EmailNotificationSender with @Component so Spring can find it.

2
Add NotificationService class with constructor injection
Create a class called NotificationService annotated with @Service. Add a private final field called notificationSender of type NotificationSender. Create a constructor that takes a NotificationSender parameter and assigns it to the field.
Spring Boot
Need a hint?

Use @Service annotation and create a constructor that takes NotificationSender and assigns it to the private final field.

3
Explain why to avoid field injection
Add a comment inside NotificationService above the field notificationSender explaining why field injection (using @Autowired on fields) is discouraged. Mention issues like difficulty in testing and hidden dependencies.
Spring Boot
Need a hint?

Write a comment above the field explaining that field injection hides dependencies and makes testing harder, while constructor injection is better.

4
Use NotificationSender in NotificationService method
Add a public method notifyUser(String message) in NotificationService that calls send(message) on the notificationSender field.
Spring Boot
Need a hint?

Create a method notifyUser that calls send on the injected notificationSender.