@Component、@Repository和@Service注释是否可以在Spring中互换使用,或者它们除了充当符号设备之外,是否提供任何特定功能?

换句话说,如果我有一个Service类,并且我将注释从@Service更改为@Component,它的行为是否仍然相同?

或者注释是否也会影响类的行为和功能?


当前回答

@Component:你注释一个类@Component,它告诉hibernate它是一个Bean。

@Repository:您注释一个类@Repositories,它会告诉hibernate它是一个DAO类,并将其视为DAO类。意味着它使未检查的异常(从DAO方法抛出)有资格转换为SpringDataAccessException。

@服务:这告诉hibernate它是一个服务类,您将在其中使用@Transactional等服务层注释,因此hibernate将其视为服务组件。

另外,@Service是@Component的进步。假设bean类名为CustomerService,因为您没有选择XMLbean配置方式,所以您使用@Component注释了bean,以将其指示为bean。因此,在获取bean对象CustomerService cust=(CustomerService)context.getBean(“CustomerService”)时;默认情况下,Spring会将组件的第一个字符从“CustomerService”小写为“CustomerService”。您可以检索名为“customerService”的组件。但是,如果对bean类使用@Service注释,则可以通过以下方式提供特定的bean名称

@Service("AAA")
public class CustomerService{

您可以通过

CustomerService cust = (CustomerService)context.getBean("AAA");

其他回答

来自Spring文档:

@Repository注释是满足存储库的角色或原型(也称为数据访问对象或DAO)。该标记的用途之一是自动翻译异常,如异常转换中所述。Spring提供了更多的原型注释:@Component、@Service、,和@Controller@组件是任何Spring管理的组件@Repository、@Service和@Controller是@Component的专门化,用于更具体的用例(在持久性、服务和表示层)。因此,您可以使用@component注释组件类,但是,通过用@Repository、@Service或@Controller注释它们相反,您的类更适合由工具处理或与方面相关。例如,这些原型注释成为切入点的理想目标@存储库、@Service和@控制器还可以在未来版本的Spring框架。因此,如果您在使用@组件或服务层的@Service,@Service显然是更好的选择。同样,如前所述,@Repository已经支持作为自动异常转换的标记持久层。

Annotation Meaning
@Component generic stereotype for any Spring-managed component
@Repository stereotype for persistence layer
@Service stereotype for service layer
@Controller stereotype for presentation layer (spring-mvc)

@存储库@Service和@Controller用作@Component的专用化,以便更具体地使用。在此基础上,您可以将@Service替换为@Component,但在这种情况下,您会失去专用化。

1. **@Repository**   - Automatic exception translation in your persistence layer.
2. **@Service**      - It indicates that the annotated class is providing a business service to other layers within the application.

刻板印象的解释:

@服务-使用@Service注释所有服务类。这一层知道工作单位。所有业务逻辑都将在服务类中。服务层的方法通常包含在事务中。您可以从服务方法进行多个DAO调用,如果一个事务失败,所有事务都应该回滚。@Repository-使用@Repository注释所有DAO类。所有数据库访问逻辑都应该在DAO类中。@组件-使用组件原型注释其他组件(例如REST资源类)。@Autowired-让Spring使用@Autowired注释自动将其他bean连接到类中。

@组件是任何Spring管理组件的通用原型@Repository、@Service和@Controller是@Component的专门化,用于更具体的用例,例如,分别在持久性、服务和表示层中。

最初在这里回答。

@Component、@Service、@Controller、@Repository之间没有区别。@Component是表示MVC组件的泛型注释。但作为MVC应用程序的一部分,将有几个组件,如服务层组件、持久层组件和表示层组件。所以为了区分它们,Spring的人也给出了其他三个注释。

表示持久层组件:@Repository表示服务层组件:@service表示表示层组件:@Controller否则,您可以对所有组件使用@Component。

@组件在配置类中充当@Bean注释,在spring上下文中注册Bean。它也是@Service、@Repository和@Controller注释的父级。

@服务,扩展了@Component注释,只有命名差异。

@Repository-扩展@Component注释并将所有数据库异常转换为DataAccessException。

@控制器-在MVC模式中充当控制器。分派器将扫描这些带注释的类以查找映射方法,检测@RequestMapping注释。