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

后端 未结 29 2600
时光说笑
时光说笑 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

    They are almost the same - all of them mean that the class is a Spring bean. @Service, @Repository and @Controller are specialized @Components. You can choose to perform specific actions with them. For example:

    • @Controller beans are used by spring-mvc
    • @Repository beans are eligible for persistence exception translation

    Another thing is that you designate the components semantically to different layers.

    One thing that @Component offers is that you can annotate other annotations with it, and then use them the same way as @Service.

    For example recently I made:

    @Component
    @Scope("prototype")
    public @interface ScheduledJob {..}
    

    So all classes annotated with @ScheduledJob are spring beans and in addition to that are registered as quartz jobs. You just have to provide code that handles the specific annotation.

提交回复
热议问题