When should I use @Component instead of @Service? [closed]
Asked Answered
E

1

10

I've already read about each Spring annotation in What's the difference between @Component, @Repository & @Service annotations in Spring?

I know that @Component and @Service do almost the same inside the Spring Framework. The difference it's bounded to it's usage, so I just use @Service into the service layer where I access my repositories.

I want to know what's the better way to choose @Component instead of @Service. Note that I'm using @Component now for a factory I've created, because the factory don't need to deal with repositories.

Everyman answered 18/1, 2018 at 18:53 Comment(1)
Ultimately it doesn't matter much, just use what seems logical to you. Sometimes I use @Service on classes that don't use repositories, and only use other services.Santa
C
11

Keep in mind that these are Spring stereotypes, and should be applied as stereotypes or assumptions around one's code are usually applied.

  • If your component is a generic component, not really living at the service layer, or is accessible but could hold state, then use @Component.
  • If your component is a specific service, living at the service layer, or is accessible and does not inherently hold state, use @Service.

Spring sees both of these ultimately as @Components.

Coparcener answered 18/1, 2018 at 18:58 Comment(1)
Why the association of Component with statefulness (and vice versa)?Schoolmaster

© 2022 - 2024 — McMap. All rights reserved.