Spring @Service and @Component – the difference, my difference

According to this topic on stackoverflow, programmers (including me) often wonder about responsibilities of classes annotated with @Service and @Component. What we can find in Spring documentation:

@Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for more specific use cases

so, there isn’t any specific responsibility for @Component annotation in Spring – in my understanding.

If this isn’t specified – why not to create our own definition?

Let’s start: when we try to imagine @Component and @Service as a something touchable – what will be bigger?

right – @Component!

 

My definitions of @Service and @Component are:

@Service should be a class of service layer (service layer pattern). contain only @Repositories – for lower complexity,
@Component should be something like group for @Services. It should contains @Services, @Repositories or other @Components.

 

My definition of @Component is on the way with `composition over inheritance`.
There is also another advantage – but this will be mentioned in separate post.

Jedna myśl na temat “Spring @Service and @Component – the difference, my difference

  1. I also tried to find information about this problem, but couldn’t find anything useful. Technically there is not much difference between @Component and @Service annotations. So it’s more about terminology that you want to use.

    I usually use the classic controller-service-repository pattern, which doesn’t leave much space to any other components. If suitable I provide a few layers of services (like security service), but still, they are services, because they are connected to the business logic of the application. Sometimes though, I need a general component, like utility to compare dates. This is exactly what you can call a component and I would usually put it under the service layer or directly into the service layer. However, classes like that rarely require to be injected by DI container. And if they don’t need to be managed then they shouldn’t be. Thus I don’t use @Component annotation, because my components can be initiated manually as they usually don’t have any dependencies.

    Does it mean that @Component annotation is completely useless? Well, I wouldn’t say so. You may need it as a base when creating some new layer in your application. Or you may use when you decide with your team that is would be really good in a particular situation. So it’s definitely a good thing that Spring creators provided us with that option.

Dodaj komentarz

Twój adres email nie zostanie opublikowany. Pola, których wypełnienie jest wymagane, są oznaczone symbolem *