从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. Win10系统下插入耳机前面板无声后面板有声的处理

    问题描述: 当耳机插入后面板绿色口(注意:耳机扬声器为绿色口,红色为话筒麦克风:前后面板一样):可以听到声音,但是转到前面板插入后,无声音:调出声音面板发现声音可随音度波动 处理步骤: 1.保证插牢接 ...

  2. jquery点击按钮弹出图片

    <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8" ...

  3. R语言——ggplot2补充知识点

    案例 ggplot(head(age_data,10),aes(x=reorder(Country,age_median),y=age_median))+ geom_bar(aes(fill=Coun ...

  4. Matlab 多个版本的安装包下载、安装和激活教程 + 多套数学建模视频教程

    目录 1. 关键词 1.1. 说明 2. 下载地址 2.1. OneDrive高速云盘 2.1.1. 多版本的安装包 2.1.2. 多套数学建模的视频教程 2.2. 百度云 3. 安装教程 1. 关键 ...

  5. V7双雄-基于Virtex7XC7VX690T的高性能计算板卡解决方案

    北京太速V7双雄-基于Virtex7XC7VX690T的高性能计算板卡

  6. nodejs 更新代码自动刷新页面

    安装第三方工具: nodemon npm install --global nodemon 安装完毕后使用: 之前使用: node xxx.js 改成 nodemon xxx.js 只要通过nodem ...

  7. 关于<label>的for属性的简单探索

    在freecodecamp上HTML教程的Create a Set of Radio Buttons这一节中,看到这样一段话, It is considered best practice to se ...

  8. 启动模式:uefi, legacy,以及GRUB命令使用

    机器启动模式:uefi, legacy 设置入口:BIOS:boot mode 磁盘分区表格式: gpt uefi所使用(此种模式下,grub只能识别gpt格式的boot引导项) mbr legacy ...

  9. Django中ifequal 和ifnotequal的使用

    Django中{% ifequal A B %} 用来比较A和B两个值是否相等,{% ifnotequal A B %}` 用来比较A和B两个值是否不相等..如: {% ifequal user cu ...

  10. Test 6.24 T3 水题

    问题描述 秋之国首都下了一场暴雨,由于秋之国地势高低起伏,不少地方出现了积水. 秋之国的首都可以看成一个 n 行 m 列的矩阵,第 i 行第 j 列的位置高度为 ai,j,首都以外的地方的高度可以都看 ...