Spring中@Component详解

Spring中@Component详解

java 中注解,与反射,泛型一样,同属元编程。而相较于反射作用类对象,泛型活在参数类型化征途,注解简直不要太自在,这从它的出生(定义), @interface ,便知不能独立生存,时刻与被注解对象在一起,是一种紧耦合,声明式编程方式。本文旨在阐述 @component 注解与其同类注解(如 @service ) 的异同。

官方

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 中 该类注解用途,但没讲明,有些情况下它们为什么可以互用

  • 强调一点 ,对于 BeanDefinition 自动扫描检测和依赖注入,所有这些注解(即 @ Component,@ Service,@ Repository,@ Controller )都是相同的,它们彼此可以相互替换

差异

  • @Component 的特殊之处
    • 是一个通用的构造型注解,表明该类是一个 spring 组件
    • <context:component-scan> 仅在于扫描 @Component 并且不会查找 @Controller@Service@Repository 一般而言。扫描它们是因为它们本身都带有注释 @Component , 看源码定义便知
@Component
public @interface Service {
    ….
}
@Component
public @interface Repository {
    ….
}
@Component
public @interface Controller {
    …
}

spring 中存在一批注解的注解,类似组合设计,有些注解只是其他注解的组合(如 RestController = Response+Controller ),有些注解则是配合主注解(如条件注解)

  • @Controller,@Service 并且 @Repository 是特殊类型的 @Component 注解。
  • <context:component-scan> 选择它们并将它们的后续类注册为 bean ,就像它们被注解一样 @Component
  • 还会扫描特殊类型的注释,因为它们本身都带有 @Component 注解的注解

@Repository

  • 表明该类定义了一个数据存储库
  • 除了指出这是一个基于注解的配置之外, @Repository 会捕获平台特定的异常并将它们重新抛出作为 Spring 统一的未经检查的异常 之一。通常需要在 spring 的应用程序上下文中添加如下配置 PersistenceExceptionTranslationPostProcessor
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

@Controller

  • @Controller 被注解的类扮演控制器的角色
  • 不同于 @Service,@Repository 注解,程序调度器扫描该注解的类,在内部会去检测其用 @RequestMapping 注解的方法

配置 xml vs 注解

注解在其声明中提供了大量上下文,从而导致更短更简洁的配置。XML 擅长在不触及源代码或重新编译它们的情况下连接组件。 spring 中的注解和 xml 配置,以及所谓的 java 配置类,最终将被 spring ioc 容器内,表示为 BeanDefinition 对象,环境对象, profile 等相关的其它对象实例

  • 注解:是一种分散式的元数据,与源代码紧绑定
  • xml:是一种集中式的元数据,与源代码无绑定
  • 让 xm 有用的是,使用 xml 的类。同样让注解有效的是 注解处理器 ,否则注解和注释没什么区别。
  • 注解这种机制是一种与 Java 编程语言无关的独立存在,它会让 java 语言更好,但不是语言必须的部分

原文:@Component 详解 | Server 运维论坛
作者: pardon110