在Spring中,@Component、@Repository & @Service注解之间有什么区别?

@Component'、@Repository'和`@Service'注解是否可以在Spring中互换使用,或者它们除了作为一种符号设备外,还提供任何特殊的功能?

换句话说,如果我有一个服务类,我把注解从"@Service "改为"@Component",它的行为是否仍然一样?

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

来自Spring Documentation

在Spring 2.0及以后的版本中,@Repository注解是一个标记,用于标记 任何满足存储库角色或定型的类(也被称为数据 访问对象或DAO)的类。这个标记的用途包括 是异常的自动翻译。

Spring 2.5引入了进一步的定型标记。@Component, @Service, 和 @Controller@Component是一个通用的定型,用于任何 Spring管理的组件。@Repository',@Service', 和@Controller'都是 @Component`的特殊化,用于更具体的使用情况,例如 例如,在持久化、服务和表现层。 分别。

因此,你可以用@Component来注解你的组件类。 但是通过用@Repository@Service@Controller来注解它们 相反,你的类更适合于被工具处理 或与方面相关联。例如,这些定型注解 是指向性的理想目标。

因此,如果你要在使用@Component'或@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)      │
└────────────┴─────────────────────────────────────────────────────┘
评论(12)

它们几乎是一样的--都意味着该类是一个Spring Bean。@Service@Repository@Controller是专门的@Component。你可以选择用它们来执行特定的动作。比如说。

  • @Controller豆被spring-mvc使用。
  • @Repository豆有资格进行持久化异常转换

另一件事是,你从语义上将组件指定给不同的层。

@Component提供的一点是,你可以用它来注解其他注解,然后以与@Service相同的方式使用它们。

例如,最近我做了。

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

因此,所有用@ScheduledJob注解的类都是spring beans,除此之外,还被注册为石英作业。你只需要提供处理特定注释的代码。

评论(3)

从数据库连接的角度来看,使用"@Service "和"@Repository "注解很重要。

1.在你所有的网络服务类型的数据库连接中使用@Service。 2.2.对所有的存储过程数据库连接使用"@Repository"。

如果你不使用适当的注释,你可能会面临被回滚事务覆盖的提交异常。在压力负载测试中,你会看到与回滚JDBC事务有关的异常。

评论(2)