Spring有@Component注释,注释@Repository,@ Service,@ Controller的真正目的是什么?

Spring has @Component annotation, what is the real purpose of the annotations @Repository, @Service, @Controller?

本问题已经有最佳答案,请猛点这里访问。

我用Spring框架开发Web应用程序已经有几年了。最近,我的一个新团队问我一个问题,Spring有@Component注释,注释@Repository@Service@Controller的真正用途是什么?我试图给他答案,他们之间没有区别,只是为了识别Java bean的类型。如你所知,我的解释缺乏说服力,他没有接受。

所以我想问一个问题,注释@Repository@Service@Controller的真正目的是什么?这些注释之间真正的区别是什么?


以前有人问过这个问题:@component,@repository&;@service annotations在春季有什么区别?

In Spring 2.0 and later, the @Repository annotation is a marker for
any class that fulfills the role or stereotype (also known as Data
Access Object or DAO) of a repository. Among the uses of this marker
is the automatic translation of exceptions.

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.

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.