美文网首页
SpringIoc源码之invokeBeanFactoryPos

SpringIoc源码之invokeBeanFactoryPos

作者: 乙腾 | 来源:发表于2020-10-09 08:23 被阅读0次

前言

1.本次看Spring源码也不说是为了学习设计模式,架构思想,只是为了扩展自己的眼界。
2.其实本次看Spring源码的时候真的特别懵,看了半天也不知道到底应该如何看,看的效率特别低,这可能是最开始看Spring源码的共性问题,我一直在想这块进度那么慢,到底为什么,后来在看了几个帖子之后终于意识到了一个问题,我没有将Spring源码看做一个单独的只是去看待,平时一直都只是在使用,而没有看过源码,几乎已经忽视了一个事实,就是我根本没有对Spring的原理知识的积累,对其中的一些重要基础数据结构和概念完完全不知道,导致我在看Spring源码的时候进度非常慢且不得其法,所以为了更好地了解Spring源码必须先要从其基础的概念作为切入点进行学习。

看Spring源码必须要提前知道的知识点

BeanDefiniton

image.png

官网对之描述比较不那么好理解,所以这里我对于BeanDefine(BeanDefiniton)的理解为:

Spring中用来存储Bean定义的元数据的一个数据结构。

补充说明:

Spring实例化Bean会通过依据BeanDefine来的定义来实例化对象,即Spring将创建对象分为了两部分

1.定义

2.按照定义实例化

类比

docker先定义后创建容器,k8s先定义后创建pods。

Spring的容器

是Spring的一个用来存储Spring启动后信息的一种数据结构,具体体现为:DefaultListableBeanFactory 。

image.png

Spring's default implementation of the {@link ConfigurableListableBeanFactory} and {@link BeanDefinitionRegistry} interfaces: a full-fledged bean factory based on bean definition metadata, extensible through post-processors

Spring的{@link ConfigurableListableBeanFactory}和{@link BeanDefinitionRegistry}接口的缺省实现:一个基于bean定义元数据的成熟的bean工厂,可通过后处理器扩展。

用来存储BeanDefine的工厂。为key,map结构。

Spring的实例化Bean的流程图

image.png

Spring创建对象的过程

前面介绍BeanDefine的时候说过,分为两部分:

1.定义

2.按照定义实例化

Spring扩展点

所有带postProcessor的都是Spring的扩展点。

Spring看源码的正确姿势

看好所有的注释

BeanDefine加载过程

1.BeanDefine扫描和注册

2.BeanDefine占位符按照配置(配置文件或配置类)的实际值替换。

Spring源码之BeanDefine的加载

<pre style="margin: 8px 0px; font-family: Consolas; font-size: 0.817rem;"> <pre style="margin: 8px 0px; font-family: Consolas;">invokeBeanFactoryPostProcessors(beanFactory);</pre> </pre>

<pre style="margin: 8px 0px; font-family: Consolas; font-size: 0.817rem;">这个方法主要用来实现BeanDefine的加载到容器中,即BeanDefine加载到DefaultListableBeanFactory 中。
</pre>

方法逻辑

<pre style="margin: 8px 0px;">这个方法里面的逻辑主要可以分为两部分</pre>

1.BeanDefine的****扫描,解析,注册

通过BeanDefinitionRegistryPostProcessor接口的

postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)

方法,完成外置配置和内置配置的扫描和解析成beanDefine,并注册到BeanFactory(DefaultListableBeanFactory容器) 中。

notice:

此时的BeanDefine中的属性值为

"${demo.constant.user.age}"</pre>

这类占位符

2.BeanDefine配置的加载,解析,并将BeanDefine中的展位符替换成实际配置中的值

通过beanFactoryPostProcessors接口的

postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)

方法,完成beanDefine 属性的解析,即将占位符替换成实际值。

相关知识点

BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessors

uml图


image.png
BeanFactoryPostProcessors

是一个BeanFactory的扩展点,可以对BeanDefine实例化之前对其属性进行更改。

在此处方法种的作用:

将BeanDefine中的占位符替换为实际值。

本次方法中这个接口的实现为

PropertySourcesPlaceholderConfigurer的

postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory)

BeanDefinitionRegistryPostProcessor

是对BeanFactoryPostProcessors 接口的扩展,BeanDefine实例化之前修改BeanDefefine的注册表。

在此处方法种的作用:

BeanDefinitionRegistryPostProcessor完成外置配置和内置配置的扫描和解析成beanDefine,并注册到BeanFactory(DefaultListableBeanFactory容器)
本次方法在这个方法中的实现为
ConfigurationClassPostProcessor的
postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)
中的最后一步

processConfigBeanDefinitions(BeanDefinitionRegistry registry)为其实现逻辑

image.png
image.png
notcie:

postProcessBeanDefinitionRegistry这个方法的执行时机要早于postProcessBeanFactory

逻辑:

先对扫描BeanDefine并解析与注册后对之属性按照配置进行赋值。

先执行对BeanDefine的扫描和注册,后统一对BeanDefine属性值进行赋值。

invokeBeanFactoryPostProcessors(beanFactory)源码

public static void invokeBeanFactoryPostProcessors(
            ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

        // Invoke BeanDefinitionRegistryPostProcessors first, if any.
        Set<String> processedBeans = new HashSet<>();

        if (beanFactory instanceof BeanDefinitionRegistry) {
            BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
            List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
            List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

            for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
                if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
                    BeanDefinitionRegistryPostProcessor registryProcessor =
                            (BeanDefinitionRegistryPostProcessor) postProcessor;
                    registryProcessor.postProcessBeanDefinitionRegistry(registry);
                    registryProcessors.add(registryProcessor);
                }
                else {
                    regularPostProcessors.add(postProcessor);
                }
            }

            // Do not initialize FactoryBeans here: We need to leave all regular beans
            // uninitialized to let the bean factory post-processors apply to them!
            // Separate between BeanDefinitionRegistryPostProcessors that implement
            // PriorityOrdered, Ordered, and the rest.
            List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

            // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
            String[] postProcessorNames =
                    beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
            for (String ppName : postProcessorNames) {
                if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                    currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                    processedBeans.add(ppName);
                }
            }
            sortPostProcessors(currentRegistryProcessors, beanFactory);
            registryProcessors.addAll(currentRegistryProcessors);
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
            currentRegistryProcessors.clear();

            // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
            postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
            for (String ppName : postProcessorNames) {
                if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
                    currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                    processedBeans.add(ppName);
                }
            }
            sortPostProcessors(currentRegistryProcessors, beanFactory);
            registryProcessors.addAll(currentRegistryProcessors);
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
            currentRegistryProcessors.clear();

            // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
            boolean reiterate = true;
            while (reiterate) {
                reiterate = false;
                postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
                for (String ppName : postProcessorNames) {
                    if (!processedBeans.contains(ppName)) {
                        currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                        processedBeans.add(ppName);
                        reiterate = true;
                    }
                }
                sortPostProcessors(currentRegistryProcessors, beanFactory);
                registryProcessors.addAll(currentRegistryProcessors);
                invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
                currentRegistryProcessors.clear();
            }

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

        else {
            // Invoke factory processors registered with the context instance.
            invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
        }

        // Do not initialize FactoryBeans here: We need to leave all regular beans
        // uninitialized to let the bean factory post-processors apply to them!
        String[] postProcessorNames =
                beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

        // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
        // Ordered, and the rest.
        List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
        List<String> orderedPostProcessorNames = new ArrayList<>();
        List<String> nonOrderedPostProcessorNames = new ArrayList<>();
        for (String ppName : postProcessorNames) {
            if (processedBeans.contains(ppName)) {
                // skip - already processed in first phase above
            }
            else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
            }
            else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
                orderedPostProcessorNames.add(ppName);
            }
            else {
                nonOrderedPostProcessorNames.add(ppName);
            }
        }

        // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
        sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
        invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

        // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
        List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
        for (String postProcessorName : orderedPostProcessorNames) {
            orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
        }
        sortPostProcessors(orderedPostProcessors, beanFactory);
        invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

        // Finally, invoke all other BeanFactoryPostProcessors.
        List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
        for (String postProcessorName : nonOrderedPostProcessorNames) {
            nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
        }
        invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

        // Clear cached merged bean definitions since the post-processors might have
        // modified the original metadata, e.g. replacing placeholders in values...
        beanFactory.clearMetadataCache();
    }

在这个源码按照之前说的拆成两部分来看

postProcessBeanDefinitionRegistry

执行
的postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)

public static void invokeBeanFactoryPostProcessors(
            ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

        // Invoke BeanDefinitionRegistryPostProcessors first, if any.
        //存放BeanDefine的集合
        Set<String> processedBeans = new HashSet<>();
        //@1 先判断是否为BeanDefinitionRegistry,因为beanFactory是DefaultListableBeanFactory, ,是BeanDefinitionRegistry的实现类肯定满足条件
        if (beanFactory instanceof BeanDefinitionRegistry) {
            BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
            //@2 定义两个BeanFactoryPostProcessor,BeanDefinitionRegistryPostProcessor类型的集合
            List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
            List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
            //正常这个beanFactoryPostProcessors集合一般情况下都是空的,除非我们手动调用容器的addBeanFactoryPostProcessor方法
            for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
                if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
                    BeanDefinitionRegistryPostProcessor registryProcessor =
                            (BeanDefinitionRegistryPostProcessor) postProcessor;
                    registryProcessor.postProcessBeanDefinitionRegistry(registry);
                    registryProcessors.add(registryProcessor);
                }
                else {
                    regularPostProcessors.add(postProcessor);
                }
            }

            // Do not initialize FactoryBeans here: We need to leave all regular beans
            // uninitialized to let the bean factory post-processors apply to them!
            // Separate between BeanDefinitionRegistryPostProcessors that implement
            // PriorityOrdered, Ordered, and the rest.
            //临时变量用来存储BeanDefinitionRegistryPostProcessor集合,对BeanDefinitionRegistryPostProcessor会有三段操作逻辑,为了避免重复创建这个集合,用这个临时变量来存储每段逻辑的变量值,并在最后清空。
            List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

            // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
            //@3 筛选PriorityOrdered类型的Bean,并对之进行排序,和注册
            String[] postProcessorNames =
                    beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
            //@3.1 晒选所有实现PriorityOrdered接口的BeanDefine,并放到currentRegistryProcessors集合中,和processedBeans集合中
            for (String ppName : postProcessorNames) {
                if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                    currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                    processedBeans.add(ppName);
                }
            }
            //@3.2 根据ordered接口进行排序
            sortPostProcessors(currentRegistryProcessors, beanFactory);
            //@3.3 将实现PriorityOrdered接口的BeanDefine集合赋值给registryProcessors集合
            registryProcessors.addAll(currentRegistryProcessors);
            //@3.4  执行BeanDefinitionRegistryPostProcessor 的BeanDefinitionRegistryPostProcessors方法
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
            //@3.5 清空临时变量
            currentRegistryProcessors.clear();

            // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
            //@4 逻辑和上面一样,筛选Ordered类型BeanDefine,然后排序,注册。
            postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
            for (String ppName : postProcessorNames) {
                if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
                    currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                    processedBeans.add(ppName);
                }
            }
            sortPostProcessors(currentRegistryProcessors, beanFactory);
            registryProcessors.addAll(currentRegistryProcessors);
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
            currentRegistryProcessors.clear();

            // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
            //@5 对没有实现PriorityOrdered和Ordered的BeanDefine,进行筛选,排序,注册
            boolean reiterate = true;
            while (reiterate) {
                reiterate = false;
                postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
                for (String ppName : postProcessorNames) {
                    if (!processedBeans.contains(ppName)) {
                        currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                        processedBeans.add(ppName);
                        reiterate = true;
                    }
                }
                sortPostProcessors(currentRegistryProcessors, beanFactory);
                registryProcessors.addAll(currentRegistryProcessors);
                invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
                currentRegistryProcessors.clear();
            }

            // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
            
            //@6 这里开始执行单独实现了BeanFactoryPostProcessor接口的后置处理器
            //先执行实现了BeanDefinitionRegistryPostProcessor的BeanFactoryPostProcessor,在前面的逻辑中只执行了BeanDefinitionRegistryPostProcessor特有的postProcessBeanDefinitionRegistry方法,它的postProcessBeanFactory方法还没有被执行,它会在这里被执行
            invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
            //执行直接实现了BeanFactoryPostProcessor接口的后置处理器
            invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
           
        }

        else {
            // Invoke factory processors registered with the context instance.
            invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
        }

        
    }

补充说明

@3.4 执行BeanDefinitionRegistryPostProcessor 的BeanDefinitionRegistryPostProcessors方法
ConfigurationClassPostProcessor的

@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
    int registryId = System.identityHashCode(registry);
    if (this.registriesPostProcessed.contains(registryId)) {
        throw new IllegalStateException(
            "postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
    }
    if (this.factoriesPostProcessed.contains(registryId)) {
        throw new IllegalStateException(
            "postProcessBeanFactory already called on this post-processor against " + registry);
    }
    this.registriesPostProcessed.add(registryId);

    processConfigBeanDefinitions(registry);
}

主要来看最后一个方法processConfigBeanDefinitions(registry);

public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
        List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
        String[] candidateNames = registry.getBeanDefinitionNames();

        for (String beanName : candidateNames) {
            BeanDefinition beanDef = registry.getBeanDefinition(beanName);
            if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
                }
            }
            else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
                configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
            }
        }

        // Return immediately if no @Configuration classes were found
        if (configCandidates.isEmpty()) {
            return;
        }

        // Sort by previously determined @Order value, if applicable
        configCandidates.sort((bd1, bd2) -> {
            int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
            int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
            return Integer.compare(i1, i2);
        });

        // Detect any custom bean name generation strategy supplied through the enclosing application context
        SingletonBeanRegistry sbr = null;
        if (registry instanceof SingletonBeanRegistry) {
            sbr = (SingletonBeanRegistry) registry;
            if (!this.localBeanNameGeneratorSet) {
                BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(
                        AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR);
                if (generator != null) {
                    this.componentScanBeanNameGenerator = generator;
                    this.importBeanNameGenerator = generator;
                }
            }
        }

        if (this.environment == null) {
            this.environment = new StandardEnvironment();
        }

        // Parse each @Configuration class
        ConfigurationClassParser parser = new ConfigurationClassParser(
                this.metadataReaderFactory, this.problemReporter, this.environment,
                this.resourceLoader, this.componentScanBeanNameGenerator, registry);

        Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
        Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
        do {
            StartupStep processConfig = this.applicationStartup.start("spring.context.config-classes.parse");
            parser.parse(candidates);
            parser.validate();

            Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
            configClasses.removeAll(alreadyParsed);

            // Read the model and create bean definitions based on its content
            if (this.reader == null) {
                this.reader = new ConfigurationClassBeanDefinitionReader(
                        registry, this.sourceExtractor, this.resourceLoader, this.environment,
                        this.importBeanNameGenerator, parser.getImportRegistry());
            }
            this.reader.loadBeanDefinitions(configClasses);
            alreadyParsed.addAll(configClasses);
            processConfig.tag("classCount", () -> String.valueOf(configClasses.size())).end();

            candidates.clear();
            if (registry.getBeanDefinitionCount() > candidateNames.length) {
                String[] newCandidateNames = registry.getBeanDefinitionNames();
                Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
                Set<String> alreadyParsedClasses = new HashSet<>();
                for (ConfigurationClass configurationClass : alreadyParsed) {
                    alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
                }
                for (String candidateName : newCandidateNames) {
                    if (!oldCandidateNames.contains(candidateName)) {
                        BeanDefinition bd = registry.getBeanDefinition(candidateName);
                        if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
                                !alreadyParsedClasses.contains(bd.getBeanClassName())) {
                            candidates.add(new BeanDefinitionHolder(bd, candidateName));
                        }
                    }
                }
                candidateNames = newCandidateNames;
            }
        }
        while (!candidates.isEmpty());

        // Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
        if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
            sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
        }

        if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
            // Clear cache in externally provided MetadataReaderFactory; this is a no-op
            // for a shared cache since it'll be cleared by the ApplicationContext.
            ((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
        }
    }

这里主要来看BeanDefine是如何被解析的
parser.parse(candidates);

public void parse(Set<BeanDefinitionHolder> configCandidates) {
        for (BeanDefinitionHolder holder : configCandidates) {
            BeanDefinition bd = holder.getBeanDefinition();
            try {
                //v注解的BeanDefine进入这个if
                if (bd instanceof AnnotatedBeanDefinition) {
                    parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
                }
                else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {
                    parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());
                }
                else {
                    parse(bd.getBeanClassName(), holder.getBeanName());
                }
            }
            catch (BeanDefinitionStoreException ex) {
                throw ex;
            }
            catch (Throwable ex) {
                throw new BeanDefinitionStoreException(
                        "Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);
            }
        }

        this.deferredImportSelectorHandler.process();
    }

parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());

protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {
        processConfigurationClass(new ConfigurationClass(metadata, beanName), DEFAULT_EXCLUSION_FILTER);
    }

实现逻辑

protected void processConfigurationClass(ConfigurationClass configClass, Predicate<String> filter) throws IOException {
    if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
        return;
    }

    ConfigurationClass existingClass = this.configurationClasses.get(configClass);
    if (existingClass != null) {
        if (configClass.isImported()) {
            if (existingClass.isImported()) {
                existingClass.mergeImportedBy(configClass);
            }
            // Otherwise ignore new imported config class; existing non-imported class overrides it.
            return;
        }
        else {
            // Explicit bean definition found, probably replacing an import.
            // Let's remove the old one and go with the new one.
            this.configurationClasses.remove(configClass);
            this.knownSuperclasses.values().removeIf(configClass::equals);
        }
    }

    // Recursively process the configuration class and its superclass hierarchy.
    SourceClass sourceClass = asSourceClass(configClass, filter);
    do {
        sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter);
    }
    while (sourceClass != null);

    this.configurationClasses.put(configClass, configClass);
}

来看doProcessConfigurationClass方法

这里实际就是对BeanDefine的解析,通过解析@ComponentScan @Import @Bean注解来实现BeanDefine的解析
这里如果发现类有被@Compoent标注,就会进行解析。
Set<BeanDefinitionHolder> scannedBeanDefinitions =
this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
这步逻辑正是对@Compoen标注类的扫描和注册

public Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, final String declaringClass) {
       ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,
               componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);

       Class<? extends BeanNameGenerator> generatorClass = componentScan.getClass("nameGenerator");
       boolean useInheritedGenerator = (BeanNameGenerator.class == generatorClass);
       scanner.setBeanNameGenerator(useInheritedGenerator ? this.beanNameGenerator :
               BeanUtils.instantiateClass(generatorClass));

       ScopedProxyMode scopedProxyMode = componentScan.getEnum("scopedProxy");
       if (scopedProxyMode != ScopedProxyMode.DEFAULT) {
           scanner.setScopedProxyMode(scopedProxyMode);
       }
       else {
           Class<? extends ScopeMetadataResolver> resolverClass = componentScan.getClass("scopeResolver");
           scanner.setScopeMetadataResolver(BeanUtils.instantiateClass(resolverClass));
       }

       scanner.setResourcePattern(componentScan.getString("resourcePattern"));

       for (AnnotationAttributes filter : componentScan.getAnnotationArray("includeFilters")) {
           for (TypeFilter typeFilter : typeFiltersFor(filter)) {
               scanner.addIncludeFilter(typeFilter);
           }
       }
       for (AnnotationAttributes filter : componentScan.getAnnotationArray("excludeFilters")) {
           for (TypeFilter typeFilter : typeFiltersFor(filter)) {
               scanner.addExcludeFilter(typeFilter);
           }
       }

       boolean lazyInit = componentScan.getBoolean("lazyInit");
       if (lazyInit) {
           scanner.getBeanDefinitionDefaults().setLazyInit(true);
       }

       Set<String> basePackages = new LinkedHashSet<>();
       String[] basePackagesArray = componentScan.getStringArray("basePackages");
       for (String pkg : basePackagesArray) {
           String[] tokenized = StringUtils.tokenizeToStringArray(this.environment.resolvePlaceholders(pkg),
                   ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
           Collections.addAll(basePackages, tokenized);
       }
       for (Class<?> clazz : componentScan.getClassArray("basePackageClasses")) {
           basePackages.add(ClassUtils.getPackageName(clazz));
       }
       if (basePackages.isEmpty()) {
           basePackages.add(ClassUtils.getPackageName(declaringClass));
       }

       scanner.addExcludeFilter(new AbstractTypeHierarchyTraversingFilter(false, false) {
           @Override
           protected boolean matchClassName(String className) {
               return declaringClass.equals(className);
           }
       });
       return scanner.doScan(StringUtils.toStringArray(basePackages));
   }
image.png
image.png
image.png

主要来看最后这步扫描

/**
     * Perform a scan within the specified base packages,
     * returning the registered bean definitions.
     * <p>This method does <i>not</i> register an annotation config processor
     * but rather leaves this up to the caller.
     * @param basePackages the packages to check for annotated classes
     * @return set of beans registered if any for tooling registration purposes (never {@code null})
     */
    protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
        Assert.notEmpty(basePackages, "At least one base package must be specified");
        Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
        for (String basePackage : basePackages) {
            //@1 扫描出被@Component标注的类
            Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
            for (BeanDefinition candidate : candidates) {
                ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
                candidate.setScope(scopeMetadata.getScopeName());
                String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
                //@2 为符合条件的Bean赋予默认值
                if (candidate instanceof AbstractBeanDefinition) {
                     //内部会设置默认值
                    postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
                }
                if (candidate instanceof AnnotatedBeanDefinition) {
                    ////如果是AnnotatedBeanDefinition,还会再设置一次值
                    AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
                }
                //@3  对BeanDefine进行注册,将doProcessConfigurationClass方法中每个遍历的Bean注册到容器中
                if (checkCandidate(beanName, candidate)) {
                    BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
                    definitionHolder =
                            AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
                    beanDefinitions.add(definitionHolder);
                    registerBeanDefinition(definitionHolder, this.registry);
                }
            }
        }
        return beanDefinitions;
    }
image.png

这里其实还可以再看一下如何扫描发现@Component标注的类
findCandidateComponents(basePackage);

private Set<BeanDefinition> scanCandidateComponents(String basePackage) {
        Set<BeanDefinition> candidates = new LinkedHashSet<>();
        try {
            //把 传进来的类似 命名空间形式的字符串转换成类似类文件地址的形式,然后在前面加上classpath*:
            //即:com.xx=>classpath*:com/xx/**/*.class
            String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                    resolveBasePackage(basePackage) + '/' + this.resourcePattern;
            //根据packageSearchPath,获得符合要求的文件
            Resource[] resources = getResourcePatternResolver().getResources(packageSearchPath);
            boolean traceEnabled = logger.isTraceEnabled();
            boolean debugEnabled = logger.isDebugEnabled();
            //循环资源
            for (Resource resource : resources) {
                if (traceEnabled) {
                    logger.trace("Scanning " + resource);
                }

                if (resource.isReadable()) {//判断资源是否可读,并且不是一个目录
                    try {
                        //metadataReader 元数据读取器,解析resource,也可以理解为描述资源的数据结构
                        MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource);
                        //在isCandidateComponent方法内部会真正执行匹配规则
                        //注册配置类自身会被排除,不会进入到这个if
                        if (isCandidateComponent(metadataReader)) {
                            ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
                            sbd.setResource(resource);
                            sbd.setSource(resource);
                            if (isCandidateComponent(sbd)) {
                                if (debugEnabled) {
                                    logger.debug("Identified candidate component class: " + resource);
                                }
                                candidates.add(sbd);
                            }
                            else {
                                if (debugEnabled) {
                                    logger.debug("Ignored because not a concrete top-level class: " + resource);
                                }
                            }
                        }
                        else {
                            if (traceEnabled) {
                                logger.trace("Ignored because not matching any filter: " + resource);
                            }
                        }
                    }
                    catch (Throwable ex) {
                        throw new BeanDefinitionStoreException(
                                "Failed to read candidate component class: " + resource, ex);
                    }
                }
                else {
                    if (traceEnabled) {
                        logger.trace("Ignored because not readable: " + resource);
                    }
                }
            }
        }
        catch (IOException ex) {
            throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
        }
        return candidates;
    }

总结

以上就是
postProcessBeanDefinitionRegistry的执行逻辑,主要介绍了
postProcessBeanDefinitionRegistry的执行逻辑,这段逻辑主要体现在doProcessConfigurationClass方法中,这里实际按照被@component,@import,@bean注解进行解析,其中重点介绍了
@componen的解析逻辑,先扫描符合条件的类,并将之注册到容器中,同时递归这个被标注的类看里面是否有被上面三个注解标注的方法。

BeanFactoryPostProcessor

这部分源码可以按照以上分析逻辑去看

// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
String[] postProcessorNames =
    beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
    if (processedBeans.contains(ppName)) {
        // skip - already processed in first phase above
    }
    else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
        priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
    }
    else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
        orderedPostProcessorNames.add(ppName);
    }
    else {
        nonOrderedPostProcessorNames.add(ppName);
    }
}

// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String postProcessorName : orderedPostProcessorNames) {
    orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

// Finally, invoke all other BeanFactoryPostProcessors.
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String postProcessorName : nonOrderedPostProcessorNames) {
    nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

// Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values...
beanFactory.clearMetadataCache();

notice:

执行BeanDefinitionRegistryPostProcessor 之前


image.png

执行BeanDefinitionRegistryPostProcessor之后


image.png
执行beanFactoryPostProcessors之后 image.png

相关文章

网友评论

      本文标题:SpringIoc源码之invokeBeanFactoryPos

      本文链接:https://www.haomeiwen.com/subject/twwkpktx.html