I think both @Component and @Service can be used to detect bean automatically, anyone can show me the difference between those two annotations?
The basic difference between both annotations is that @Service is a specialization of @Component.
See also spring documentation for @Service:
Indicates that an annotated class is a "Service" (e.g. a business service facade).
This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.
A specialization of component is also a @Repository and a @Controller
Further information can be found e.g. here.
As of and up to Spring 3.1, there is no difference in the way that Spring handles them. The docs say this, but in a rather obscure way:
Spring 2.5 introduces further stereotype annotations:
@Component,@Service, and@Controller.@Componentis a generic stereotype for any Spring-managed component.@Repository,@Service, and@Controllerare specializations of@Componentfor more specific use cases, for example, in the persistence, service, and presentation layers, respectively. Therefore, you can annotate your component classes with@Component, but by annotating them with@Repository,@Service, or@Controllerinstead, your classes are more properly suited for processing by tools or associating with aspects. For example, these stereotype annotations make ideal targets for pointcuts. It is also possible that@Repository,@Service, and@Controllermay carry additional semantics in future releases of the Spring Framework. Thus, if you are choosing between using@Componentor@Servicefor your service layer,@Serviceis clearly the better choice. Similarly, as stated above,@Repositoryis already supported as a marker for automatic exception translation in your persistence layer.
So for now, @Service will be treated by Spring exactly the same as @Component, but @Service can be considered a form of documentation.
I'm not really sure why @Service was included in Spring 2.5 at all, since it doesn't seem to have any really purpose.
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