@Component'、
@Repository'和`@Service'注解是否可以在Spring中互换使用,或者它们除了作为一种符号设备外,还提供任何特殊的功能?
换句话说,如果我有一个服务类,我把注解从"@Service "改为"@Component",它的行为是否仍然一样?
或者注释也会影响类的行为和功能?
在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) │
└────────────┴─────────────────────────────────────────────────────┘
它们几乎是一样的--都意味着该类是一个Spring Bean。@Service
、@Repository
和@Controller
是专门的@Component
。你可以选择用它们来执行特定的动作。比如说。
@Controller
豆被spring-mvc使用。@Repository
豆有资格进行持久化异常转换另一件事是,你从语义上将组件指定给不同的层。
@Component
提供的一点是,你可以用它来注解其他注解,然后以与@Service
相同的方式使用它们。
例如,最近我做了。
@Component
@Scope("prototype")
public @interface ScheduledJob {..}
因此,所有用@ScheduledJob
注解的类都是spring beans,除此之外,还被注册为石英作业。你只需要提供处理特定注释的代码。