Performance: Constructor injection (preferred)
This affects application startup time and memory usage by managing dependency creation efficiently.
public class Service {
private final Repository repo;
public Service(Repository repo) {
this.repo = repo;
}
}public class Service {
@Autowired
private Repository repo;
public Service() {}
}| Pattern | Reflection Usage | Startup Delay | Memory Overhead | Verdict |
|---|---|---|---|---|
| Field Injection (@Autowired on fields) | High | Medium | Higher due to proxies | [X] Bad |
| Constructor Injection (preferred) | Low | Low | Lower | [OK] Good |
constructor injection in Spring Boot?printMessage method is called?\@Component
public class Printer {
private final MessageService service;
public Printer(MessageService service) {
this.service = service;
}
public void printMessage() {
System.out.println(service.getMessage());
}
}
\@Component
public class MessageService {
public String getMessage() {
return "Hello Spring!";
}
}\@Component
public class UserService {
private final UserRepository repo;
public UserService() {
this.repo = null;
}
}PaymentService and NotificationService. How should you write the constructor to follow best practices for constructor injection?Pass the test and this pattern moves unknown