• Spring源码------IOC容器初始化过程


    前言 

    IOC容器的初始化过程,我这边分为两大步

    1.容器的初始化

    AnnotationConfigApplicationContext annotationConfigApplicationContext = new AnnotationConfigApplicationContext(MyConfig.class);

    ​​​​​​​ 

     2.Bean的创建

    Food food = annotationConfigApplicationContext.getBean("food", Food.class);

    ​​​​​​​ 

    1.容器的初始化

    1.1初始化DefaultListableBeanFactory

    AnnotationConfigApplicationContext继承GenericApplicationContext,所以在初始化AnnotationConfigApplicationContext的时候,会先调用父类GenericApplicationContext的构造函数,而 DefaultListableBeanFactory实现了BeanDefinitionRegistry,所以最终AnnotationConfigApplicationContext既是一个BeanFactory,也是一个BeanDefinitionRegistry

    1. public GenericApplicationContext() {
    2. this.beanFactory = new DefaultListableBeanFactory();
    3. }

    1.2初始化reader

    this.reader = new AnnotatedBeanDefinitionReader(this);

    该方法最主要的作用就是注册内置的五个BeanDefinition到BeanDefinitionMap中,重点关注前两个

    ConfigurationClassPostProcessor[实现BeanDefinitionRegistryPostProcessor]
    
    AutowiredAnnotationBeanPostProcessor[实现BeanPostProcessor]
    CommonAnnotationBeanPostProcessor[实现BeanPostProcessor]
    EventListenerMethodProcessor[实现BeanFactoryPostProcessor]
    DefaultEventListenerFactory
    1. public static Set registerAnnotationConfigProcessors(
    2. BeanDefinitionRegistry registry, @Nullable Object source) {
    3. DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
    4. if (beanFactory != null) {
    5. if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
    6. beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
    7. }
    8. if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
    9. beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
    10. }
    11. }
    12. Set beanDefs = new LinkedHashSet<>(8);
    13. if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
    14. RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
    15. def.setSource(source);
    16. beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
    17. }
    18. if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
    19. RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
    20. def.setSource(source);
    21. beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
    22. }
    23. // Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
    24. if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
    25. RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
    26. def.setSource(source);
    27. beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
    28. }
    29. // Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
    30. if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
    31. RootBeanDefinition def = new RootBeanDefinition();
    32. try {
    33. def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
    34. AnnotationConfigUtils.class.getClassLoader()));
    35. }
    36. catch (ClassNotFoundException ex) {
    37. throw new IllegalStateException(
    38. "Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
    39. }
    40. def.setSource(source);
    41. beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
    42. }
    43. if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
    44. RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
    45. def.setSource(source);
    46. beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
    47. }
    48. if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
    49. RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
    50. def.setSource(source);
    51. beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
    52. }
    53. return beanDefs;
    54. }

    1.3初始化scanner

    该scanner只有显式调用才会用到,不重要

    annotationConfigApplicationContext.scan("com.lyf.study");

    1.4注册传入的配置类MyConfig

    1. public void register(Class... componentClasses) {
    2. for (Class componentClass : componentClasses) {
    3. registerBean(componentClass);
    4. }
    5. }

    最终会到AnnotatedBeanDefinitionReader中的doRegisterBean方法中

    关键步骤如下:

    1.4.1解析@Conditional注解,判断配置类是否满足加载条件,不满足则直接跳过

    1. if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
    2. return;
    3. }

    1.4.2将配置类注册到BeanDefinitionMap中

    BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);

    1.5执行refresh的invokeBeanFactoryPostProcessor

    1.5.1执行手动添加的BeanDefinitionRegistryPostProcessor

     若手动注册为BeanDefinitionRegistryPostProcessor,则先执行其postProcessBeanDefinitionRegistry方法

    注:BeanFactoryPostProcessor是BeanDefinitionRegistryPostProcessor的父类

    BeanFactoryPostProcessor

    有postProcessBeanFactory方法,主要用于修改BeanDefinitionMap中的BeanDefinition

    BeanDefinitionRegistryPostProcessor

    有postProcessBeanDefinitionRegistry方法,主要用于添加BeanDefinition到BeanDefinitionMap中

    1. //beanFactoryPostProcessors中的所有postProcessor都是显式调用annotationConfigApplicationContext.addBeanFactoryPostProcessor(null);来的
    2. for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
    3. if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
    4. BeanDefinitionRegistryPostProcessor registryProcessor =
    5. (BeanDefinitionRegistryPostProcessor) postProcessor;
    6. registryProcessor.postProcessBeanDefinitionRegistry(registry);
    7. registryProcessors.add(registryProcessor);
    8. }
    9. else {
    10. regularPostProcessors.add(postProcessor);
    11. }
    12. }

    1.5.2 执行实现PriorityOrdered接口的BeanDefinitionRegistryPostProcessor(关键)

    1. String[] postProcessorNames =
    2. beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
    3. for (String ppName : postProcessorNames) {
    4. if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
    5. currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
    6. processedBeans.add(ppName);
    7. }
    8. }
    9. sortPostProcessors(currentRegistryProcessors, beanFactory);
    10. registryProcessors.addAll(currentRegistryProcessors);
    11. invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
    12. currentRegistryProcessors.clear();

    这里默认情况下只会获取到reader中注册的5个内置的BeanFactoryPostProcessor中的ConfigurationClassPostProcessor,然后执行ConfigurationClassPostProcessor的postProcessBeanDefinitionRegistry方法​​​​​​​ 

    ConfigurationClassPostProcessor的postProcessBeanDefinitionRegistry非常的关键,它主要做了一下几件事:

    (1)从beanFactory中获取所有已经注册到BeanDefinitionMap中的BeanDefinitionNames

    (2)给使用了@Configuration注解的BeanDefinition打上full的标识[后续会使用cglib增强],给使用了@Order注解的BeanDefinition打上优先等级

    (3)将符合(2)的所有BeanDefinition放入configCandidates列表中

    (4)对configCandidates列表中的BeanDefinition,依据order属性值排序,值越小,优先级越高

    (5)构建ConfigurationClassParser,解析每一个使用@Configuration的类,内部会对@Component、@PropertySource、@ComponentScan、@Import、@ImportResource、@Bean注解做处理

    (6)将解析出来的对象转成BeanDefintion注册到BeanDefinitionMap中

    1.5.3 执行实现PriorityOrdered接口的BeanDefinitionRegistryPostProcessor

    1. postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
    2. for (String ppName : postProcessorNames) {
    3. if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
    4. currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
    5. processedBeans.add(ppName);
    6. }
    7. }
    8. sortPostProcessors(currentRegistryProcessors, beanFactory);
    9. registryProcessors.addAll(currentRegistryProcessors);
    10. invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
    11. currentRegistryProcessors.clear();

    1.5.4执行剩下的BeanDefinitionRegistryPostProcessor

    1. // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
    2. boolean reiterate = true;
    3. while (reiterate) {
    4. reiterate = false;
    5. postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
    6. for (String ppName : postProcessorNames) {
    7. if (!processedBeans.contains(ppName)) {
    8. currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
    9. processedBeans.add(ppName);
    10. reiterate = true;
    11. }
    12. }
    13. sortPostProcessors(currentRegistryProcessors, beanFactory);
    14. registryProcessors.addAll(currentRegistryProcessors);
    15. invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
    16. currentRegistryProcessors.clear();
    17. }

    1.5.5执行所有BeanDefinitionRegistryPostProcessor的postProcessBeanFactory

    1. // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
    2. invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
    3. invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);

    1.5.6执行所有BeanFactoryPostProcessor的postProcessBeanFactory

    1. String[] postProcessorNames =
    2. beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
    3. // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
    4. // Ordered, and the rest.
    5. List priorityOrderedPostProcessors = new ArrayList<>();
    6. List orderedPostProcessorNames = new ArrayList<>();
    7. List nonOrderedPostProcessorNames = new ArrayList<>();
    8. for (String ppName : postProcessorNames) {
    9. if (processedBeans.contains(ppName)) {
    10. // skip - already processed in first phase above
    11. }
    12. else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
    13. priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
    14. }
    15. else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
    16. orderedPostProcessorNames.add(ppName);
    17. }
    18. else {
    19. nonOrderedPostProcessorNames.add(ppName);
    20. }
    21. }
    22. // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
    23. sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    24. invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
    25. // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
    26. List orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
    27. for (String postProcessorName : orderedPostProcessorNames) {
    28. orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    29. }
    30. sortPostProcessors(orderedPostProcessors, beanFactory);
    31. invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
    32. // Finally, invoke all other BeanFactoryPostProcessors.
    33. List nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
    34. for (String postProcessorName : nonOrderedPostProcessorNames) {
    35. nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    36. }
    37. invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
    38. // Clear cached merged bean definitions since the post-processors might have
    39. // modified the original metadata, e.g. replacing placeholders in values...
    40. beanFactory.clearMetadataCache();

    1.6执行refresh的registerBeanPostProcessors方法

    依据内置的AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor对应的BeanDefinition,生成相对应的Bean,并添加到容器中

    • BeanDefinitionRegistryPostProcessor

            最先执行,主要用于添加BeanDefinition

    • BeanFactoryPostProcessor

            次要执行,主要用于修改BeanDefinition

    • BeanPostProcessor

            最后执行,在Bean初始化前会调用postProcessBeforeInitialization,在Bean初始化之后会                    调用postProcessAfterInitialization

    至此,容器大致的初始化过程结束.

    2.Bean的创建

  • 相关阅读:
    关于web3营销的一切知识
    [C语言趣编程]抓小偷问题
    【【萌新的FPGA学习之实战流水灯】】
    多线程事务在Junit、Mybatis中使用
    【Cherno的OpenGL视频】Creating tests in OpenGL
    Android MVI架构的深入解析与对比
    JSP共享自习室管理系统84w25--(程序+源码+数据库+调试部署+开发环境)
    什么是HTTP/2?它与HTTP/1.1相比有什么改进?
    Pytorch迁移学习训练病变分类模型
    【C++】类和对象(上)
  • 原文地址:https://blog.csdn.net/chengtanyong4777/article/details/126473425