从Spring2.0 以后的版本中,Spring 也引入了基于注解(Annotation)方式的配置,注解(Annotation)是JDK1.5 中引入的一个新特性,用于简化Bean 的配置,可以取代XML 配置文件。开发人员对注解(Annotation)的态度也是萝卜青菜各有所爱,个人认为注解可以大大简化配置,提高开发速度,但也给后期维护增加了难度。目前来说XML 方式发展的相对成熟,方便于统一管理。随着Spring Boot 的兴起,基于注解的开发甚至实现了零配置。但作为个人的习惯而言,还是倾向于XML 配置文件和注解(Annotation)相互配合使用。Spring IOC 容器对于类级别的注解和类内部的注解分以下两种处理策略:

1)、类级别的注解:如@Component、@Repository、@Controller、@Service 以及JavaEE6 的@ManagedBean 和@Named 注解,都是添加在类上面的类级别注解,Spring 容器根据注解的过滤规则扫描读取注解Bean 定义类,并将其注册到Spring IOC 容器中。

2)、类内部的注解:如@Autowire、@Value、@Resource 以及EJB 和WebService 相关的注解等,都是添加在类内部的字段或者方法上的类内部注解,SpringIOC 容器通过Bean 后置注解处理器解析Bean 内部的注解。下面将根据这两种处理策略,分别分析Spring 处理注解相关的源码。

定位Bean 扫描路径:

  在Spring 中管理注解Bean 定义的容器有两个: AnnotationConfigApplicationContext 和AnnotationConfigWebApplicationContex。这两个类是专门处理Spring 注解方式配置的容器,直接依赖于注解作为容器配置信息来源的IOC 容器。AnnotationConfigWebApplicationContext 是AnnotationConfigApplicationContext 的Web 版本,两者的用法以及对注解的处理方式几乎没有差别。现在我们以AnnotationConfigApplicationContext 为例看看它的源码:

public class AnnotationConfigApplicationContext extends GenericApplicationContext implements AnnotationConfigRegistry {
//保存一个读取注解的Bean 定义读取器,并将其设置到容器中
private final AnnotatedBeanDefinitionReader reader;
//保存一个扫描指定类路径中注解Bean 定义的扫描器,并将其设置到容器中
private final ClassPathBeanDefinitionScanner scanner; //默认构造函数,初始化一个空容器,容器不包含任何Bean 信息,需要在稍后通过调用其register()
//方法注册配置类,并调用refresh()方法刷新容器,触发容器对注解Bean 的载入、解析和注册过程
public AnnotationConfigApplicationContext() {
this.reader = new AnnotatedBeanDefinitionReader(this);
this.scanner = new ClassPathBeanDefinitionScanner(this);
} //最常用的构造函数,通过将涉及到的配置类传递给该构造函数,以实现将相应配置类中的Bean 自动注册到容器中
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
this();
register(annotatedClasses);
refresh();
}
//该构造函数会自动扫描以给定的包及其子包下的所有类,并自动识别所有的Spring Bean,将其注册到容器中
public AnnotationConfigApplicationContext(String... basePackages) {
this();
scan(basePackages);
refresh();
} //为容器注册一个要被处理的注解Bean,新注册的Bean,必须手动调用容器的
//refresh()方法刷新容器,触发容器对新注册的Bean 的处理
public void register(Class<?>... annotatedClasses) {
Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified");
this.reader.register(annotatedClasses);
} public void scan(String... basePackages) {
Assert.notEmpty(basePackages, "At least one base package must be specified");
this.scanner.scan(basePackages);
}
}

  通过上面的源码分析,我们可以看啊到Spring 对注解的处理分为两种方式:

1)、直接将注解Bean 注册到容器中可以在初始化容器时注册;也可以在容器创建之后手动调用注册方法向容器注册,然后通过手动刷新容器,使得容器对注册的注解Bean 进行处理。

2)、通过扫描指定的包及其子包下的所有类在初始化注解容器时指定要自动扫描的路径,如果容器创建以后向给定路径动态添加了注解Bean,则需要手动调用容器扫描的方法,然后手动刷新容器,使得容器对所注册的Bean 进行处理。接下来,将会对两种处理方式详细分析其实现过程。

读取Annotation 元数据:

  当创建注解处理容器时,如果传入的初始参数是具体的注解Bean 定义类时,注解容器读取并注册。

1)、AnnotationConfigApplicationContext 通过调用注解Bean 定义读取器AnnotatedBeanDefinitionReader 的register()方法向容器注册指定的注解Bean,注解Bean 定义读取器向容器注册注解Bean 的源码如下:

//Bean 定义读取器向容器注册注解Bean 定义类
<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
@Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {
//根据指定的注解Bean 定义类,创建Spring 容器中对注解Bean 的封装的数据结构
AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
return;
} abd.setInstanceSupplier(instanceSupplier);
//解析注解Bean 定义的作用域,若@Scope("prototype"),则Bean 为原型类型;
//若@Scope("singleton"),则Bean 为单态类型
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
//为注解Bean 定义设置作用域
abd.setScope(scopeMetadata.getScopeName());
//为注解Bean 定义设置bean名称
String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
//处理注解Bean 定义中的通用注解
AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
if (qualifiers != null) {
//如果在向容器注册注解Bean 定义时,使用了额外的限定符注解,则解析限定符注解。
//主要是配置的关于autowiring 自动依赖注入装配的限定条件,即@Qualifier 注解
//Spring 自动依赖注入装配默认是按类型装配,如果使用@Qualifier 则按名称
for (Class<? extends Annotation> qualifier : qualifiers) {
//如果配置了@Primary 注解,设置该Bean 为autowiring 自动依赖注入装//配时的首选
if (Primary.class == qualifier) {
abd.setPrimary(true);
}
//如果配置了@Lazy 注解,则设置该Bean 为非延迟初始化,如果没有配置,
//则该Bean 为预实例化
else if (Lazy.class == qualifier) {
abd.setLazyInit(true);
}
//如果使用了除@Primary 和@Lazy 以外的其他注解,则为该Bean 添加一
//个autowiring 自动依赖注入装配限定符,该Bean 在进autowiring
//自动依赖注入装配时,根据名称装配限定符指定的Bean
else {
abd.addQualifier(new AutowireCandidateQualifier(qualifier));
}
}
}
for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
customizer.customize(abd);
}
//创建一个指定Bean 名称的Bean 定义对象,封装注解Bean 定义类数据
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
//根据注解Bean 定义类中配置的作用域,创建相应的代理对象
definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
//向IOC 容器注册注解Bean 类定义对象
BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}

  从上面的源码我们可以看出,注册注解Bean 定义类的基本步骤:

a、需要使用注解元数据解析器解析注解Bean 中关于作用域的配置。

b、使用AnnotationConfigUtils 的processCommonDefinitionAnnotations()方法处理注解Bean 定义类中通用的注解。

c、使用AnnotationConfigUtils 的applyScopedProxyMode()方法创建对于作用域的代理对象。

d、通过BeanDefinitionReaderUtils 向容器注册Bean。

  下面我们继续分析这4 步的具体实现过程

2)、AnnotationScopeMetadataResolver 解析作用域元数据

  AnnotationScopeMetadataResolver 通过resolveScopeMetadata()方法解析注解Bean 定义类的作用域元信息,即判断注册的Bean 是原生类型(prototype)还是单态(singleton)类型,其源码如下:

//解析注解Bean 定义类中的作用域元信息
@Override
public ScopeMetadata resolveScopeMetadata(BeanDefinition definition) {
ScopeMetadata metadata = new ScopeMetadata();
if (definition instanceof AnnotatedBeanDefinition) {
//从注解Bean 定义类的属性中查找属性为”Scope”的值,即@Scope 注解的值
//annDef.getMetadata().getAnnotationAttributes 方法将Bean
//中所有的注解和注解的值存放在一个map 集合中
AnnotatedBeanDefinition annDef = (AnnotatedBeanDefinition) definition;
AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(
annDef.getMetadata(), this.scopeAnnotationType);
//将获取到的@Scope 注解的值设置到要返回的对象中
if (attributes != null) {
metadata.setScopeName(attributes.getString("value"));
ScopedProxyMode proxyMode = attributes.getEnum("proxyMode");
//如果@Scope 的proxyMode 属性为DEFAULT 或者NO
if (proxyMode == ScopedProxyMode.DEFAULT) {
//设置proxyMode 为NO
proxyMode = this.defaultProxyMode;
}
metadata.setScopedProxyMode(proxyMode);
}
}
return metadata;
}

  上述代码中的annDef.getMetadata().getAnnotationAttributes()方法就是获取对象中指定类型的注解的值。

3)、AnnotationConfigUtils 处理注解Bean 定义类中的通用注解

  AnnotationConfigUtils 类的processCommonDefinitionAnnotations()在向容器注册Bean 之前,首先对注解Bean 定义类中的通用Spring 注解进行处理,源码如下:

static void processCommonDefinitionAnnotations(AnnotatedBeanDefinition abd, AnnotatedTypeMetadata metadata) {
AnnotationAttributes lazy = attributesFor(metadata, Lazy.class);
//如果Bean 定义中有@Lazy 注解,则将该Bean 预实例化属性设置为@lazy 注解的值
if (lazy != null) {
abd.setLazyInit(lazy.getBoolean("value"));
}
else if (abd.getMetadata() != metadata) {
lazy = attributesFor(abd.getMetadata(), Lazy.class);
if (lazy != null) {
abd.setLazyInit(lazy.getBoolean("value"));
}
}
//如果Bean 定义中有@Primary 注解,则为该Bean 设置为autowiring 自动依赖注入装配的首选对象
if (metadata.isAnnotated(Primary.class.getName())) {
abd.setPrimary(true);
}
//如果Bean 定义中有@ DependsOn 注解,则为该Bean 设置所依赖的Bean 名称,
//容器将确保在实例化该Bean 之前首先实例化所依赖的Bean
AnnotationAttributes dependsOn = attributesFor(metadata, DependsOn.class);
if (dependsOn != null) {
abd.setDependsOn(dependsOn.getStringArray("value"));
} if (abd instanceof AbstractBeanDefinition) {
AbstractBeanDefinition absBd = (AbstractBeanDefinition) abd;
AnnotationAttributes role = attributesFor(metadata, Role.class);
if (role != null) {
absBd.setRole(role.getNumber("value").intValue());
}
AnnotationAttributes description = attributesFor(metadata, Description.class);
if (description != null) {
absBd.setDescription(description.getString("value"));
}
}
}

4)、AnnotationConfigUtils 根据注解Bean 定义类中配置的作用域为其应用相应的代理策略

  AnnotationConfigUtils 类的applyScopedProxyMode()方法根据注解Bean 定义类中配置的作用域@Scope 注解的值,为Bean 定义应用相应的代理模式,主要是在Spring 面向切面编程(AOP)中使用。源码如下:

static BeanDefinitionHolder applyScopedProxyMode(
ScopeMetadata metadata, BeanDefinitionHolder definition, BeanDefinitionRegistry registry) {
//获取注解Bean 定义类中@Scope 注解的proxyMode 属性值
ScopedProxyMode scopedProxyMode = metadata.getScopedProxyMode();
//如果配置的@Scope 注解的proxyMode 属性值为NO,则不应用代理模式
if (scopedProxyMode.equals(ScopedProxyMode.NO)) {
return definition;
}
//获取配置的@Scope 注解的proxyMode 属性值,如果为TARGET_CLASS
//则返回true,如果为INTERFACES,则返回false
boolean proxyTargetClass = scopedProxyMode.equals(ScopedProxyMode.TARGET_CLASS);
//为注册的Bean 创建相应模式的代理对象
return ScopedProxyCreator.createScopedProxy(definition, registry, proxyTargetClass);
}

  这段为Bean 引用创建相应模式的代理,这里不做深入的分析。

5)、BeanDefinitionReaderUtils 向容器注册Bean

  BeanDefinitionReaderUtils 主要是校验BeanDefinition 信息,然后将Bean 添加到容器中一个管理BeanDefinition 的HashMap 中。

扫描指定包并解析为BeanDefinition

  当创建注解处理容器时,如果传入的初始参数是注解Bean 定义类所在的包时,注解容器将扫描给定的包及其子包,将扫描到的注解Bean 定义载入并注册。

1)、ClassPathBeanDefinitionScanner 扫描给定的包及其子包

  AnnotationConfigApplicationContext 通过调用类路径Bean 定义扫描器ClassPathBeanDefinitionScanner 扫描给定包及其子包下的所有类.

protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
Assert.notEmpty(basePackages, "At least one base package must be specified");
//创建一个集合,存放扫描到Bean 定义的封装类
Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
//遍历扫描所有给定的包
for (String basePackage : basePackages) {
//调用父类ClassPathScanningCandidateComponentProvider 的方法
//扫描给定类路径,获取符合条件的Bean 定义
Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
//遍历扫描到的Bean
for (BeanDefinition candidate : candidates) {
//获取Bean 定义类中@Scope 注解的值,即获取Bean 的作用域
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
//为Bean 设置注解配置的作用域
candidate.setScope(scopeMetadata.getScopeName());
//为Bean 生成名称
String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
//如果扫描到的Bean 不是Spring 的注解Bean,则为Bean 设置默认值,
//设置Bean 的自动依赖注入装配属性等
if (candidate instanceof AbstractBeanDefinition) {
postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
}
//如果扫描到的Bean 是Spring 的注解Bean,则处理其通用的Spring 注解
if (candidate instanceof AnnotatedBeanDefinition) {
//处理注解Bean 中通用的注解,在分析注解Bean 定义类读取器时已经分析过
AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
}
//根据Bean 名称检查指定的Bean 是否需要在容器中注册,或者在容器中冲突
if (checkCandidate(beanName, candidate)) {
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
//根据注解中配置的作用域,为Bean 应用相应的代理模式
definitionHolder =
AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
beanDefinitions.add(definitionHolder);
//向容器注册扫描到的Bean
registerBeanDefinition(definitionHolder, this.registry);
}
}
}
return beanDefinitions;
}

  类路径Bean 定义扫描器ClassPathBeanDefinitionScanner 主要通过findCandidateComponents()方法调用其父类ClassPathScanningCandidateComponentProvider 类来扫描获取给定包及其子包下的类。

2)、ClassPathScanningCandidateComponentProvider 扫描给定包及其子包的类

  ClassPathScanningCandidateComponentProvider 类的findCandidateComponents()方法具体实现扫描给定类路径包的功能.

  最后通过扫描到的类进行解析注册,流程与直接注册Bean类似。

基于Annotation的IOC 初始化的更多相关文章

  1. Spring - IoC(8): 基于 Annotation 的配置

    除了基于 XML 的配置外,Spring 也支持基于 Annotation 的配置.Spring 提供以下介个 Annotation 来标注 Spring Bean: @Component:标注一个普 ...

  2. Spring IOC初始化深度解析

    1.前言 本文是基于JAVA配置方法对Spring IOC进行分析,掌握Spring IOC初始化流程对于我们更好的使用Spring.学习Spring还是很有帮助的,本文所使用的的Spring版本为5 ...

  3. 10 Spring框架--基于注解的IOC配置

    1.工程环境搭建 2.基于注解的IOC配置 IOC注解的分类 (1)用于创建对象的 他们的作用就和在XML配置文件中编写一个<bean>标签实现的功能是一样的@Component: 作用: ...

  4. 基于 Annotation 拦截的 Spring AOP 权限验证方法

    基于 Annotation 拦截的 Spring AOP 权限验证方法 转自:http://www.ibm.com/developerworks/cn/java/j-lo-springaopfilte ...

  5. 详解 Spring 3.0 基于 Annotation 的依赖注入实现(转)

    使用 @Repository.@Service.@Controller 和 @Component 将类标识为 Bean Spring 自 2.0 版本开始,陆续引入了一些注解用于简化 Spring 的 ...

  6. 详解 Spring 3.0 基于 Annotation 的依赖注入实现--转载

    使用 @Repository.@Service.@Controller 和 @Component 将类标识为 Bean Spring 自 2.0 版本开始,陆续引入了一些注解用于简化 Spring 的 ...

  7. Spring基于 Annotation 的简单介绍

    tyle="margin:20px 0px 0px; font-size:14px; line-height:26px; font-family:Arial"> 1.使用 @ ...

  8. 详解 Spring 3.0 基于 Annotation 的依赖注入实现

    Spring 的依赖配置方式与 Spring 框架的内核自身是松耦合设计的.然而,直到 Spring 3.0 以前,使用 XML 进行依赖配置几乎是唯一的选择.Spring 3.0 的出现改变了这一状 ...

  9. Spring 框架的概述以及Spring中基于XML的IOC配置

    Spring 框架的概述以及Spring中基于XML的IOC配置 一.简介 Spring的两大核心:IOC(DI)与AOP,IOC是反转控制,DI依赖注入 特点:轻量级.依赖注入.面向切面编程.容器. ...

随机推荐

  1. spark sql 创建DataFrame

    SQLContext是创建DataFrame和执行SQL语句的入口 通过RDD结合case class转换为DataFrame 1.准备:hdfs上提交一个文件,schema为id name age, ...

  2. 身为一个小白,看到一篇值得看的文章。讲述小白学习python的6个方法。

    01. Python怎么学?   Python虽然号称非常简单,功能强大!但是再简单,它也是一门编程语言,任何一个编程语言都会包含: 内功,心法和招式,内功心法就是指的算法,数据结构: 招式就是任何一 ...

  3. 基于 VirtualApp 结合 whale hook框架实现hook第三方应用

    要点 1. whale hook framework 使用示例: 2. 参考项目:VirtualHook: 3. 按照 VirtualHook 修改 VirtualApp: 4. 编写 hook pl ...

  4. 团队中的 Git 实践

    转载自:https://segmentfault.com/a/1190000004963641 本文首发于欧雷流.由于我会时不时对文章进行补充.修正和润色,为了保证所看到的是最新版本,请阅读原文. 在 ...

  5. [POI2008]BLO(Tarjan)

    [POI2008]BLO Description Byteotia城市有\(n\)个 towns \(m\)条双向roads. 每条 road 连接 两个不同的 towns ,没有重复的road. 所 ...

  6. Vuex 学习笔记一

    一.定义 Vuex是一个专为Vue.js应用程序开发的状态管理模式. 状态管理模式 简单的demo new Vue({ // state data () { return { count: 0 } } ...

  7. flask之注册功能

    一:注册功能 1:前端准备表单 # 前端代码 <!DOCTYPE html> <html lang="en"> <head> <meta ...

  8. Python---基础---dict和set2

    2019-05-21 写一个程序来管理用户登陆系统的用户信息:登陆名字和密码,登陆用户账号建立后,已存在用户可以用登陆名字和密码重返系统,新用户不能用别人的用户名建立用户账号 ------------ ...

  9. 【leetcode】1079. Letter Tile Possibilities

    题目如下: You have a set of tiles, where each tile has one letter tiles[i]printed on it.  Return the num ...

  10. centos 7 网卡绑定 bond0 开机无法自启

    https://blog.csdn.net/u012881151/article/details/54910847 1.环境CentOS Linux release 7.2.1511 (Core)li ...