文章目录

  • 实例化容器
  • 源码分析
    • this
      • 调用父类的构造函数
      • 然后调用自己的构造函数
        • new AnnotatedBeanDefinitionReader(this);
        • new ClassPathBeanDefinitionScanner(this);
    • register(annotatedClasses);


实例化容器

AnnotationConfigApplicationContext ctx = new    AnnotationConfigApplicationContext(App.class);

源码分析

进去看一下

public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {//调用构造函数this();//注册我们的配置类register(annotatedClasses);//IOC容器刷新接口refresh();}

这里我们分析一下AnnotationConfigApplicationContext 构造函数中的前两个方法

  • this()
  • register(annotatedClasses);

this

调用父类的构造函数

调用AnnotationConfigApplicationContext无参的构造器,会先调用父类GenericApplicationContext的无参构造器

public GenericApplicationContext() {//创建IOC容器 ,用于存放beanthis.beanFactory = new DefaultListableBeanFactory();}

调用父类的构造方法 生成一个IOC容器,主要是存放bean定义


然后调用自己的构造函数

public AnnotationConfigApplicationContext() {StartupStep createAnnotatedBeanDefReader = this.getApplicationStartup().start("spring.context.annotated-bean-reader.create");/*** 初始化注解模式下的bean定义扫描器  * 调用AnnotatedBeanDefinitionReader构造方法,传入的是this(AnnotationConfigApplicationContext)对象*/this.reader = new AnnotatedBeanDefinitionReader(this);createAnnotatedBeanDefReader.end();/*** 初始化我们的classPath类型的bean定义扫描器*/this.scanner = new ClassPathBeanDefinitionScanner(this);}

我们看下这里面主要的方法

new AnnotatedBeanDefinitionReader(this);

跟进去

public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {this(registry, getOrCreateEnvironment(registry));}

就是为bean定义读取器赋值,

那毫无疑问 先getOrCreateEnvironment(registry) ---- 创建环境

 /*** Get the Environment from the given registry if possible, otherwise return a new* StandardEnvironment.*/private static Environment getOrCreateEnvironment(BeanDefinitionRegistry registry) {Assert.notNull(registry, "BeanDefinitionRegistry must not be null");if (registry instanceof EnvironmentCapable) {return ((EnvironmentCapable) registry).getEnvironment();}return new StandardEnvironment();}

然后继续this方法的调用 ,

 public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {Assert.notNull(registry, "BeanDefinitionRegistry must not be null");Assert.notNull(environment, "Environment must not be null");this.registry = registry;this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);}

第一步

this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);

创建一个条件计算器对象 ,用于处理 条件表达式计算 @Conditionl注解


第二步 , 为容器中注册系统的bean定义信息 ,这些后置处理器 是Spring开天辟地初始化内部beandefinition的地方, 没有这个,就没有IOC,非常重要。

AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);

来跟进去

public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(BeanDefinitionRegistry registry, @Nullable Object source) {DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);if (beanFactory != null) {if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {//注册了实现Order接口的排序器beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);}//设置@AutoWired的候选的解析器if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());}}Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);/*** 为我们容器中注册了解析我们配置类的后置处理器ConfigurationClassPostProcessor* 名字叫:org.springframework.context.annotation.internalConfigurationAnnotationProcessor*/if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);def.setSource(source);beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));}/*** 为我们容器中注册了处理@Autowired 注解的处理器AutowiredAnnotationBeanPostProcessor* 名字叫:org.springframework.context.annotation.internalAutowiredAnnotationProcessor*/if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);def.setSource(source);beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));}/*** 为我们容器中注册处理@Required属性的注解处理器RequiredAnnotationBeanPostProcessor* 名字叫:org.springframework.context.annotation.internalRequiredAnnotationProcessor*/if (!registry.containsBeanDefinition(REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {RootBeanDefinition def = new RootBeanDefinition(RequiredAnnotationBeanPostProcessor.class);def.setSource(source);beanDefs.add(registerPostProcessor(registry, def, REQUIRED_ANNOTATION_PROCESSOR_BEAN_NAME));}/*** 为我们容器注册处理JSR规范的注解处理器CommonAnnotationBeanPostProcessor* org.springframework.context.annotation.internalCommonAnnotationProcessor*/if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);def.setSource(source);beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));}/*** 处理jpa注解的处理器org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor*/if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {RootBeanDefinition def = new RootBeanDefinition();try {def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,AnnotationConfigUtils.class.getClassLoader()));}catch (ClassNotFoundException ex) {throw new IllegalStateException("Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);}def.setSource(source);beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));}/*** 处理监听方法的注解解析器EventListenerMethodProcessor*/if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);def.setSource(source);beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));}/*** 注册事件监听器工厂*/if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);def.setSource(source);beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));}return beanDefs;}

new ClassPathBeanDefinitionScanner(this);

简言之 初始化我们的classPath类型的bean定义扫描器

/*** ClassPathBeanDefinitionScanner就是用来扫描我们classpath下的标注了@Service @Compent @Respository @Controller* 注解* @param environment 环境对象* definition profile metadata* @param resourceLoader the {@link ResourceLoader} to use* @since 4.3.6*/public ClassPathBeanDefinitionScanner(BeanDefinitionRegistry registry, boolean useDefaultFilters,Environment environment, @Nullable ResourceLoader resourceLoader) {Assert.notNull(registry, "BeanDefinitionRegistry must not be null");this.registry = registry;/*** 设置默认的扫描规则为true的话 默认是扫描所有的  若使用 includeFilters 来表示只包含需要设置为false*/if (useDefaultFilters) {registerDefaultFilters();}//设置环境对象setEnvironment(environment);//设置资源加载器setResourceLoader(resourceLoader);}

我们来关注下 registerDefaultFilters();

/*** 这也是为啥我们标注了@Compent @Repository @Service @Controller 能够被识别解析* <p>Also supports Java EE 6's {@link javax.annotation.ManagedBean} and* JSR-330's {@link javax.inject.Named} annotations, if available.**/@SuppressWarnings("unchecked")protected void registerDefaultFilters() {//加入扫描我们的@Component的this.includeFilters.add(new AnnotationTypeFilter(Component.class));ClassLoader cl = ClassPathScanningCandidateComponentProvider.class.getClassLoader();try {//加入扫描我们的JSR250规范的this.includeFilters.add(new AnnotationTypeFilter(((Class<? extends Annotation>) ClassUtils.forName("javax.annotation.ManagedBean", cl)), false));logger.debug("JSR-250 'javax.annotation.ManagedBean' found and supported for component scanning");}catch (ClassNotFoundException ex) {// JSR-250 1.1 API (as included in Java EE 6) not available - simply skip.}try {//加入扫描我们JSR330规范的this.includeFilters.add(new AnnotationTypeFilter(((Class<? extends Annotation>) ClassUtils.forName("javax.inject.Named", cl)), false));logger.debug("JSR-330 'javax.inject.Named' annotation found and supported for component scanning");}catch (ClassNotFoundException ex) {// JSR-330 API not available - simply skip.}}

支持分析完了this(),接下来看看 register(annotatedClasses);


register(annotatedClasses);

看名字,也能猜到 是注册我们的配置类的方法。

其实

 public void register(Class<?>... annotatedClasses) {Assert.notEmpty(annotatedClasses, "At least one annotated class must be specified");this.reader.register(annotatedClasses);}

继续 register

 public void register(Class<?>... annotatedClasses) {for (Class<?> annotatedClass : annotatedClasses) {registerBean(annotatedClass);}}

可以看到是支持多个配置类的,

 public void registerBean(Class<?> annotatedClass) {doRegisterBean(annotatedClass, null, null, null);}

我们发现Spring真正干活的方法都是do开头的。。。。。,所以重点关注

继续

/*** Register a bean from the given bean class, deriving its metadata from* class-declared annotations.* * @since 5.0*/<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,@Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {return;}abd.setInstanceSupplier(instanceSupplier);ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);abd.setScope(scopeMetadata.getScopeName());String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);if (qualifiers != null) {for (Class<? extends Annotation> qualifier : qualifiers) {if (Primary.class == qualifier) {abd.setPrimary(true);}else if (Lazy.class == qualifier) {abd.setLazyInit(true);}else {abd.addQualifier(new AutowireCandidateQualifier(qualifier));}}}for (BeanDefinitionCustomizer customizer : definitionCustomizers) {customizer.customize(abd);}// 注册自己传入的主配置类bean定义到容器中BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);}

重点就是最后几句 : 注册自己传入的主配置类bean定义到容器中

BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);

其实这个register 就是使用 AnnotatedBeanDefinitionReader实例化的过程中


public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {this(registry, getOrCreateEnvironment(registry));}

生成的bean定义读取器注册配置类


到此为止,refresh方法之前的两个方法就是这样的 ,get了么…

Spring5源码 - 00 IOC容器创建_前期准备相关推荐

  1. Spring源码:IOC容器

    Spring IOC 容器 最底层的IOC容器BeanFactory. 高级形态的IOC容器ApplicationContext. BeanFactory相关类图: ApplicationContex ...

  2. Spring5源码 - Spring IOC 注解复习

    文章目录 Pre xml配置文件 JavaConfig @CompentScan 在配置类上写@CompentScan注解来进行包扫描 excludeFilters includeFilters @C ...

  3. Spring源码分析——IOC容器

    1.IOC容器的概念 理解IOC容器的概念之前首先需要了解依赖翻转(又称依赖倒置)的概念 许多复杂的应用都是通过多个类之间的彼此合作实现业务逻辑的,这使得每个对象都需要管理自己与其合作对象的依赖,而如 ...

  4. 【框架源码】Spring源码底层IOC容器加入对象的方式

    1.Spring容器加入对象方式简介 使用XML配置文件 在XML配置文件中使用< bean >标签来定义Bean,通过ClassPathXmlApplicationContext等容器来 ...

  5. java spring ioc 实例_Spring 源码阅读(IOC容器)-bean的实例化以及注入

    3.Bean的实例化以及注入过程分析 Bean的实例以及注入是在getBean时触发的,由于外部容器是与外部调用交互的桥梁,我们首先从外部容器入手,AbstractApplicationContext ...

  6. Spring5源码 - 12 Spring事件监听机制_异步事件监听应用及源码解析

    文章目录 Pre 实现原理 应用 配置类 Event事件 事件监听 EventListener 发布事件 publishEvent 源码解析 (反推) Spring默认的事件广播器 SimpleApp ...

  7. Spring5源码 - 11 Spring事件监听机制_源码篇

    文章目录 pre 事件监听机制的实现原理[观察者模式] 事件 ApplicationEvent 事件监听者 ApplicationEvent 事件发布者 ApplicationEventMultica ...

  8. Spring5源码 - 13 Spring事件监听机制_@EventListener源码解析

    文章目录 Pre 概览 开天辟地的时候初始化的处理器 @EventListener EventListenerMethodProcessor afterSingletonsInstantiated 小 ...

  9. Spring5源码 - 05 invokeBeanFactoryPostProcessors 源码解读_3细说invokeBeanDefinitionRegistryPostProcessors

    文章目录 Pre 细说invokeBeanDefinitionRegistryPostProcessors 流程图 源码分析 解析配置类 parser.parse(candidates) 配置类注册到 ...

最新文章

  1. 两段用来启动/重启Linux下Tomcat的Perl脚本
  2. 360下载的mysql_MySQL数据库5.7
  3. Spring事务的处理流程、传播属性、及部分释疑
  4. Spring核心——Bean的生命周期
  5. USTC English Club Note20171011
  6. unity hub添加找不到文件夹_教师资格证报名网站,IE浏览器“兼容性站点”添加方法。找不到按钮怎么办?...
  7. 飞秋2010下载不仅野草是如此
  8. CMake-add_executable()
  9. oracle last day比较,PLSQL LAST_DAY用法及代码示例
  10. 高级售前客户服务专员题库
  11. 大庆金桥:基于 SpreadJS 开发实现计量器具检定证书的在线生成与打印
  12. 声学模型GMM-HMM训练
  13. codingdojo kata 之fizzbuzz
  14. 竟领先15% 解密飞行堡垒吃鸡重装版强悍性能
  15. python--正则表达式匹配密码
  16. java继承a mya new c,【转】Android应用程序完全退出
  17. 未来一年商业智能的发展前景如何?
  18. t420i升级固态硬盘提升_电脑升级固态硬盘,速度还不够快?这些设置你一定没做好...
  19. 凤凰卫视、资迅、电影台
  20. RFSoC全面解析(八)—— ZCU111 RFSoC评估工具的上位机界面

热门文章

  1. 机器学习——逻辑回归算法
  2. python中x,y=y,x的交换原理
  3. Fifth Week:Node.js学习
  4. C++ close()关闭文件方法详解
  5. deepfm算法思维导图和代码
  6. Leetcode 112. 路径总和 (每日一题 20210910)
  7. R语言实战应用精讲50篇(二十七)-R语言实现随机森林(附R语言代码)
  8. 深度学习核心技术精讲100篇(七十六)-分类-决策树
  9. MATLAB实战系列(一)-二维路径规划算法续集-图像边缘提取(附代码)
  10. 从TCP协议的原理来谈谈rst复位攻击