1.Spring Annotations
在大多数典型的应用程序中,我们有不同的层,如数据访问、展示、服务、业务等。 此外,在每一层中,我们都有各种bean。
为了自动检测这些bean,Spring 使用类路径扫描注解。 然后,它将每个bean注册到ApplicationContext中。
@Component是任何 Spring 管理的组件的通用构造型。
@Service在服务层对类进行注记。
@Repository在持久性层对类进行注释,持久性层将充当数据库存储库。
2.有什么不同
这些注解之间的主要区别在于它们用于不同的分类
2.1@Component
我们可以在整个应用进程中使用@Component将 bean 标记为 Spring 的托管组件。Spring只会选择和注册@Component 注解的beans,一般不会寻找@Service和@Repository。
它们在 ApplicationContext 中注册,因为它们带有@Component注释:
@Component
public @interface Service {
}
@Component
public @interface Repository {
}
@Service和@Repository是@Component的特殊情况。它们在技术上是相同的,但我们将它们用于不同的目的
2.2@Repository
@Repository的工作是捕获特定于持久性的异常,并将其作为Spring的统一未检查异常之一重新抛出。
为此,Spring 提供了 PersistenceExceptionTranslationPostProcessor,我们需要将其添加到我们的应用进程上下文中(如果我们使用 Spring Boot 已经包含在内):
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
这个 bean 后处理器向任何用 @Repository 注释的 bean 添加advisor。
2.3@Service
我们用@Service标记 bean,以指示它们持有业务逻辑。除了在服务图层中使用之外,此注记没有任何其他特殊用途。
3.结论
总之,根据图层约定选择注释始终是一个好主意。