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

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

    @Component, @ Repository, @ Service, @Controller:

    @Component is a generic stereotype for the components managed by Spring @Repository, @Service, and @Controller are @Component specializations for more specific uses:

    • @Repository for persistence
    • @Service for services and transactions
    • @Controller for MVC controllers

    Why use @Repository, @Service, @Controller over @Component? We can mark our component classes with @Component, but if instead we use the alternative that adapts to the expected functionality. Our classes are better suited to the functionality expected in each particular case.

    A class annotated with @Repository has a better translation and readable error handling with org.springframework.dao.DataAccessException. Ideal for implementing components that access data (DataAccessObject or DAO).

    An annotated class with @Controller plays a controller role in a Spring Web MVC application

    An annotated class with @Service plays a role in business logic services, example Facade pattern for DAO Manager (Facade) and transaction handling

提交回复
热议问题