What's the difference between @Component, @Repository & @Service annotations in Spring?

后端 未结 29 2598
时光说笑
时光说笑 2020-11-22 00:33

Can @Component, @Repository and @Service annotations be used interchangeably in Spring or do they provide any particular functionality besides acting as a notation device?

29条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-22 01:03

    We can answer this according to java standard

    Referring to JSR-330, which is now supported by spring, you can only use @Named to define a bean (Somehow @Named=@Component). So according to this standard, there seems that there is no use to define stereotypes (like @Repository, @Service, @Controller) to categories beans.

    But spring user these different annotations in different for the specific use, for example:

    1. Help developers define a better category for the competent. This categorizing may become helpful in some cases. (For example when you are using aspect-oriented, these can be a good candidate for pointcuts)
    2. @Repository annotation will add some functionality to your bean (some automatic exception translation to your bean persistence layer).
    3. If you are using spring MVC, the @RequestMapping can only be added to classes which are annotated by @Controller.

提交回复
热议问题