Spring 支持@Component、@service、@Repository 等多种类型的注解。所有这些都可以在 org.springframework.stereotype 包下找到,@Bean 可以在 org.springframework.context.annotation 包下找到。
当我们的应用程序中的类使用上述任何注释进行注释时,然后在项目启动期间弹簧扫描(使用@ComponentScan)每个类并将类的实例注入 IOC 容器。 @ComponentScan 会做的另一件事是运行带有 @Bean 的方法并将返回对象作为 bean 恢复到 Ioc 容器。
在我们深入研究(@Component vs @service vs @Repository)之前,最好先了解@Bean 和@Component 之间的区别
@Component vs @Repository vs @Service
在大多数典型应用程序中,我们有不同的层,如数据访问、表示、服务、业务等。此外,在每一层中,我们都有不同的 bean。为了自动检测这些 bean,Spring 使用类路径扫描注解。然后在 ApplicationContext 中注册每个 bean。
以下是其中一些注释的简短概述:
- @Component 是任何 Spring 管理的组件的通用构造型。
- @Service 在服务层注释类。
- @Repository 在持久层注释类,它将充当数据库存储库。
@组件注解
@Component 是一个类级别的注解。我们可以在整个应用程序中使用@Component 将bean 标记为Spring 的托管组件。 Spring 只会用@Component 获取和注册bean,一般不会查找@Service 和@Repository。
它们在 ApplicationContext 中注册,因为它们带有 @Component 注释
如上所述,@Component 是所有原型注释的父级。当 Spring 执行组件扫描时,它只查找标有 @Component 注解的类。
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {
String value() default "";
}
我们可以在所有类上使用这个注解,不会造成任何差异。
@Service 注解
我们用@Service 标记bean 以表明它们持有业务逻辑。这个注解除了用在服务层,没有其他特殊用途。
@Service 是组件的子组件,用于表示来自应用程序服务层的类。
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
@AliasFor(
annotation = Component.class
)
String value() default "";
}
@Repository 注释
@Repository 的工作是捕获特定于持久性的异常并将它们作为 Spring 统一的未检查异常之一重新抛出。
为此,Spring 提供了 PersistenceExceptionTranslationPostProcessor,我们需要将其添加到应用程序上下文中(如果我们使用 Spring Boot,则已包含):
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
此 bean 后处理器向任何使用 @Repository 注释的 bean 添加顾问。
同样,@Repository 也是组件注解的子类,用于属于持久化数据访问层的类,作为数据存储库。
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
@AliasFor(
annotation = Component.class
)
String value() default "";
}
总结
@Service 和@Repository 是@Component 的特例。它们在技术上是相同的,但我们将它们用于不同的目的。根据它们的层约定选择注释总是一个好主意。