Spring 2.5 以后,除了提供基本的 @Component
注解之外,还提供了 @Service
@Controller
@Repository
三个注解。在 Spring 源码中,后面三个注解都在开始部分引入了 @Component
注解,除此以外这四个注解的源码内容没有任何区别,因此后面的这三个注解与 Component 的作用是一样的。之所以要额外的引出这三个注解,是为了更好的与 Web 开发中常用的三层结构相对应。
// 四个注解的源码对比,此处省略了源码开头的 import 部分和注释部分
// 以下源码截取自 Spring 4.3.8 : org.springframework.stereotype 包下
// Component 源码定义
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Component {
String value() default "";
}
// Controller 源码定义
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
String value() default "";
}
// Service 源码定义
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {
String value() default "";
}
// Repository 源码定义
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {
String value() default "";
}
下面截取了 Spring 源码中对于这四个注解的一些介绍:
Indicates that an annotated class is a “component”. Such classes are considered as candidates for auto-detection when using annotation-based configuration and classpath scanning.
将一个 类 标记为 Component,这种类将会作为候选类,当使用基于注解的配置和类路径扫描的时候将会被自动检测。
Indicates that an annotated class is a “Service”, originally defined by Domain-Driven Design (Evans, 2003) as “an operation offered as an interface that stands alone in the model, with no encapsulated state.”
Indicates that an annotated class is a “Repository”, originally defined by Domain-Driven Design (Evans, 2003) as “a mechanism for encapsulating storage, retrieval, and search behavior which emulates a collection of objects”.
Indicates that an annotated class is a “Controller” (e.g. a web controller).
通过上面的源码阅读,我们可以大致的看出这四个注解之间的关系:
@Component
是基础注解,表示一个 JavaBean 可以被注入到 Spring 容器中。
为了更好的表示 Web 服务中的三层结构,所以就额外的引出了另外的三种注解分别用在三层结构中进行标注:
@Controller
用在表现层,对来自前端的请求进行转发处理与重定向。
@Repository
用在持久层,标注 DAO 类,表示这个类可以对数据库进行数据的读取或者写入。
@Service
用在业务层,用来处理业务逻辑。
引入三个注解之后,就实现了将处理前端请求、处理业务逻辑、处理数据库读写这三个基本任务进行了解耦,方便程序的编写和项目维护。
Spring 中另外的几个常见的注解的源码中的介绍
Marks a constructor, field, setter method or config method as to be autowired by Spring’s dependency injection facilities.
Annotation at the field or method/constructor parameter level that indicates a default value expression for the affected argument.
Marks a method (typically a JavaBean setter method) as being ‘required’: that is, the setter method must be configured to be dependency-injected with a value.
Marks a class as being eligible for Spring-driven configuration.
This annotation may be used on a field or parameter as a qualifier for candidate beans when autowiring. It may also be used to annotate other custom annotations that can then in turn be used as qualifiers.