S
S
Stepan2021-09-13 22:30:56
Spring
Stepan, 2021-09-13 22:30:56

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);
}

2. By implementing it, a service is created in which the method is overridden:
@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);
        }
    }
}

And then not EmailServiceImpl is injected into the SchedulerService, but the "original" EmailService:
@Slf4j
@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SchedulerService {

    private final UserRepositoryService userService; 

    private final EmailService emailService;

}

Questions that are not clear to me:
1. Is this normal?
2. Why is the "original" interface injected?
3. Why is EmailServiceImpl created if it is not used? It's not being used, is it?
4. Is there some tricky Spring magic here? Does it see that there is an InterfaceName Impl and take that into account in the process? How it works?
5. How to create interfaces in Spring and inject them correctly?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry Roo, 2021-09-13
@steff

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 question

Ask a Question

731 491 924 answers to any question