600+ Spring Interview Questions & Answers E-Book with KAPIL GAHLOT
500+ Java Interview Q&A Ebook with KAPIL GAHLOT
@Autowired
@Component
public class UserService {
// Field injection
@Autowired
private UserRepository userRepository;
// Constructor injection
@Autowired
public UserService(UserRepository userRepository) {
this.userRepository = userRepository;
}
public void saveUser(User user) {
userRepository.save(user);
}
}
@Autowired
injects the UserRepository
bean. Constructor injection is generally preferred over field injection as it makes the class easier to test.@Qualifier
@Component
public class NotificationService {
@Autowired
@Qualifier("emailService")
private MessageService messageService;
public void sendNotification(String message) {
messageService.sendMessage(message);
}
}
@Component("emailService")
public class EmailService implements MessageService {
@Override
public void sendMessage(String message) {
// Logic to send an email
}
}
@Component("smsService")
public class SmsService implements MessageService {
@Override
public void sendMessage(String message) {
// Logic to send an SMS
}
}
@Qualifier("emailService")
ensures that the EmailService
bean is injected, even though multiple implementations of MessageService
exist.