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

后端 未结 29 3011
时光说笑
时光说笑 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 00:49

    Explanation of stereotypes :

    • @Service - Annotate all your service classes with @Service. This layer knows the unit of work. All your business logic will be in Service classes. Generally methods of service layer are covered under transaction. You can make multiple DAO calls from service method, if one transaction fails all transactions should rollback.
    • @Repository - Annotate all your DAO classes with @Repository. All your database access logic should be in DAO classes.
    • @Component - Annotate your other components (for example REST resource classes) with component stereotype.
    • @Autowired - Let Spring auto-wire other beans into your classes using @Autowired annotation.

    @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.

    Originally answered here.

提交回复
热议问题