Answer the question
In order to leave comments, you need to log in
How to create and inject services correctly in Spring?
I understand with Spring, and some things are not completely clear to me. For example, a recently read article: https://habr.com/ru/post/352954/
The text provides an example of creating services:
1. The EmailService interface is created:
public interface EmailService {
void send(String to, String title, String body);
}
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class EmailServiceImpl implements EmailService {
private final JavaMailSender emailSender;
@Override
public void send(String to, String subject, String text) {
MimeMessage message = this.emailSender.createMimeMessage();
MimeMessageHelper helper = new MimeMessageHelper(message);
try {
helper.setTo(to);
helper.setSubject(subject);
helper.setText(text);
this.emailSender.send(message);
} catch (MessagingException messageException) {
throw new RuntimeException(messageException);
}
}
}
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SchedulerService {
private final UserRepositoryService userService;
private final EmailService emailService;
}
Answer the question
In order to leave comments, you need to log in
1. Yes
2. An interface is not a class or a bean - it cannot be injected. It says that you need to inject a Bean that implements the interface.
3. EmailServiceImpl will be used just because. it implements the required interface.
4. You can name the service whatever you like. The main thing is that it implements the desired interface.
5. See p2
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question