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.
We can use @Component across the application to mark the beans as Spring's managed components. Spring will only pick up and register beans with @Component, and doesn't look for @Service and @Repository in general. @Service and @Repository are special cases of @Component.
@Component is an annotation that allows Spring to automatically detect our custom beans. In other words, without having to write any explicit code, Spring will: Scan our application for classes annotated with @Component. Instantiate them and inject any specified dependencies into them.
A Spring bean in the service layer should be annotated using @Service instead of @Component annotation and a spring bean in the persistence layer should be annotated with @Repository annotation.
Keep in mind that these are Spring stereotypes, and should be applied as stereotypes or assumptions around one's code are usually applied.
@Component
.@Service
.Spring sees both of these ultimately as @Component
s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With