Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For the spring autodetection, what's the difference between component and service?

I think both @Component and @Service can be used to detect bean automatically, anyone can show me the difference between those two annotations?

like image 553
user705414 Avatar asked Jan 19 '12 08:01

user705414


2 Answers

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.

like image 103
fyr Avatar answered Oct 11 '22 19:10

fyr


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. @Component is a generic stereotype for any Spring-managed component. @Repository, @Service, and @Controller are specializations of @Component for 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 @Controller instead, 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 @Controller may carry additional semantics in future releases of the Spring Framework. Thus, if you are choosing between using @Component or @Service for your service layer, @Service is clearly the better choice. Similarly, as stated above, @Repository is 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.

like image 40
skaffman Avatar answered Oct 11 '22 17:10

skaffman