[Spring]基于注解的AnnotationConfigApplicationContext组件扫描过程

AnnotationConfigApplicationContext

在了解注解容器类之前,有必要谈谈XML容器的由来。由于早期的Java版本并没有支持注解,所以当时的Spring选择了XML这种语言来描述Bean,后续Java在1.5发布了注解后,Spring在3.0开始大批量引入Annotation。而基于注解注册和组件扫描的容器上下文即为-AnnotationConfigApplicationContext,以下是该类的注释信息:

独立的应用程序上下文,接受Component类作为输入-特别是使用@Configuration注释的类,还可以使用javax.inject注释使用普通的@Component类型和符合JSR-330的类。
允许使用register(Class ...)一对一地注册类,以及使用scan(String ...)进行类路径扫描。
如果有多个@Configuration类,则在较新的类中定义的@Bean方法将覆盖在较早的类中定义的方法。可以利用此属性通过一个额外的@Configuration类来故意覆盖某些Bean定义。

简单的注解容器demo代码

package com.xjm.bean.init;

import com.AnnotationContextDemo;
import com.xjm.controller.HelloController;
import com.xjm.model.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.Map;

/**
 * @author jaymin
 * 2020/11/28 18:19
 */
@Configuration
@ComponentScan(value = "com.xjm")
public class BeanDefinitionDemoByAnnotation {
    public static void main(String[] args) {
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AnnotationContextDemo.class);
        Person kobe = (Person) applicationContext.getBean("Kobe");
        Map beansOfType = applicationContext.getBeansOfType(Person.class);
        beansOfType.entrySet().stream().forEach(System.out::println);
        Person james = (Person) applicationContext.getBean("James");
        System.out.println(kobe.toString());
        System.out.println(james.toString());
    }
}

AnnotatedBeanDefinition

Spring为注解订制的BeanDefinition.可以从中读取到AnnotationMetadata,即注解元数据。
关于注解元数据,推荐一下这篇文章->Spring 注解编程之 AnnotationMetadata
Spring中解析配置类一般用到AnnotatedGenericBeanDefinition,其内置了StandardAnnotationMetadata来解析配置类上的注解信息.

AnnotatedBeanDefinitionReader

沿着new AnnotationConfigApplicationContext(AnnotationContextDemo.class)这段代码进入到容器上下文的初始化过程,会找到这段代码:

// this()
public AnnotationConfigApplicationContext() {
    this.reader = new AnnotatedBeanDefinitionReader(this);
    this.scanner = new ClassPathBeanDefinitionScanner(this);
}
public AnnotationConfigApplicationContext(Class... componentClasses) {
    this();
    // 注册的事情委托给了AnnotatedBeanDefinitionReader.register
    // 包装传入的 Class生成 BeanDefinition。注册到 BeanDefinitionRegistry
    register(componentClasses);
    refresh();
}
  • AnnotatedBeanDefinitionReader: 如果你读过XML的BeanDefinition的注册过程,应该清楚,解析BeanDefinition和注册BeanDefinition都是交由BeanDefinitionReader来执行的。从类的命名上我们可以得知,这是一个基于注解的BeanDefinitionReader.
  • DefaultListableBeanFactory: 不仅如此,AnnotationConfigApplicationContext还继承 了GenericApplicationContext,前文说过,调用类的初始化方法时,默认会调用父类的构造方法:
public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry {

    private final DefaultListableBeanFactory beanFactory;
    // 实例化的时候初始化DefaultListableBeanFactory
    public GenericApplicationContext() {
    this.beanFactory = new DefaultListableBeanFactory();
}
}

提前初始化DefaultListableBeanFactory是为了提前注册容器内置的BeanDefinition.
this.reader = new AnnotatedBeanDefinitionReader(this);,在这里的this指向的是AnnotationConfigApplicationContext,AnnotatedBeanDefinitionReader会将容器上下文作为registry,在注册的时候则会调用this.beanFactory.registerBeanDefinition(beanName, beanDefinition);对BeanDefinition进行注册.

register(componentClasses)流程

  • 委派AnnotatedBeanDefinitionReader进行注册
public void register(Class... componentClasses) {
Assert.notEmpty(componentClasses, "At least one component class must be specified");
this.reader.register(componentClasses);
}
  • AnnotatedBeanDefinitionReader#register

循环注册传入的多个componentClasses

public void register(Class... componentClasses) {
for (Class componentClass : componentClasses) {
    registerBean(componentClass);
}
}
  • AnnotatedBeanDefinitionReader#registerBean(java.lang.Class)

执行注册Bean的逻辑,很有意思的一件事是,Spring中doxxx()的方法,一般就是真正的执行方法。

 void doRegisterBean(Class beanClass, @Nullable Supplier instanceSupplier, @Nullable String name,
        @Nullable Class[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {
    // 将配置类装载到AnnotatedGenericBeanDefinition,通过内置的StandardAnnotationMetadata来获取注解元数据
    AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
    // 根据Condition的条件判断是否跳过该bean的注册
    if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
        return;
    }
    // 设置初始化的回调函数,传入一个函数式接口->supplier
    abd.setInstanceSupplier(instanceSupplier);
    ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
    // 解析scope的值,默认为singleton
    abd.setScope(scopeMetadata.getScopeName());
    // 判断是否含有beanName,如果没有则调用自动生成器进行生成
    String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
    // 解析部分注解: @DependsOn、@Lazy、@Primary、@Role
    AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
    // qualifier,多个实现类时,通过这个注解来区分加载的bean
    if (qualifiers != null) {
        for (Class qualifier : qualifiers) {
            if (Primary.class == qualifier) {
                abd.setPrimary(true);
            }
            else if (Lazy.class == qualifier) {
                abd.setLazyInit(true);
            }
            else {
                abd.addQualifier(new AutowireCandidateQualifier(qualifier));
            }
        }
    }
    // 用户自定义BeanDefinition,用于定制化场景
    // 自定义bean注册,手动向容器中以lambda表达式的方式注册bean
    // applicationContext.registerBean(xxxService.class, () -> new xxxService());
    for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
        customizer.customize(abd);
    }
    // 包装BeanDefinition到BeanDefinitionHolder
    BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
    // 是否需要根据scope生成动态代理对象
    definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
    // 注册BeanDefinition
    BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}

关于@Conditional的注解解释:可以参考这两篇博客:
@Conditional 原理
Spring 之 Condition 条件注解 实践和源码学习

组件扫描过程

从上文可以看到register只是注册了componentClasses,而基于这些配置类的组件扫描,则是在容器的refresh中进行处理的。这里的componentClasses指的是在配置类,即AnnotationConfigApplicationContext的构造函数中传入的配置类.

  • AbstractApplicationContext#refresh

关注这个方法,这里是注解解析注册的入口,对比XML的入口:ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();,可以发现两者的注册入口是不一样的。

// Invoke factory processors registered as beans in the context.
// 激活在容器中注册为bean的工厂处理器。
invokeBeanFactoryPostProcessors(beanFactory);
  • AbstractApplicationContext#invokeBeanFactoryPostProcessors

十分关键的方法,在这里容器会开始激活BeanFactoryPostProcessors.

    /**
     * Instantiate and invoke all registered BeanFactoryPostProcessor beans,
     * respecting explicit order if given.
     * 

Must be called before singleton instantiation.
* 实例化并调用所有注册的BeanFactoryPostProcessor Bean,并遵循显式顺序(如果给定)。
* 必须在单例实例化之前调用。 */ protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) { // 委托类处理,这里的beanFactory为DefaultListableBeanFactory PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors()); // Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor) // 如果找到一个LoadTimeWeaver,那么就准备将后置处理器"织入"bean工厂 // 例如:(一个@Bean方法通过ConfigurationClassPostProcessor来注册) if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } }

关注PostProcessorRegistrationDelegate这个委托类,这里容器将激活BeanFactoryPostProcessor的任务委托给了这个final的PostProcessorRegistrationDelegate类中的静态方法:

BeanFactoryPostProcessor

这里主要是给用户做扩展,你可以实现这个接口来对beanFactory做一些修改.

@FunctionalInterface
public interface BeanFactoryPostProcessor {

    /**
     * Modify the application context's internal bean factory after its standard
     * initialization. All bean definitions will have been loaded, but no beans
     * will have been instantiated yet. This allows for overriding or adding
     * properties even to eager-initializing beans.
     * @param beanFactory the bean factory used by the application context
     * @throws org.springframework.beans.BeansException in case of errors
     */
    void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;

}

Spring中主要有两类的BeanFactoryPostPorcessor:

  • BeanDefinitionRegistryPostProcessor: 扩展自BeanFactoryPostProcessor,执行的优先级优于一般的BeanFactoryPostProcessor,用于注册其他BeanDefinition.
  • BeanFactoryPostProcessor: 常规的BeanFactoryPostProcessor,会在BeanDefinitionRegistryPostProcessor执行完后按顺序执行。

  • PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors(
    ConfigurableListableBeanFactory beanFactory, List beanFactoryPostProcessors)
    public static void invokeBeanFactoryPostProcessors(
            ConfigurableListableBeanFactory beanFactory, List beanFactoryPostProcessors) {

        // Invoke BeanDefinitionRegistryPostProcessors first, if any.
        // 如果有BeanDefinitionRegistryPostProcessors的话优先执行
        Set processedBeans = new HashSet<>();
        // 如果是BeanDefinitionRegistry类型
        if (beanFactory instanceof BeanDefinitionRegistry) {
            BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
            // 用于记录常规的BeanFactoryPostProcessor
            List regularPostProcessors = new ArrayList<>();
            // 用于记录BeanDefinitionRegistryPostProcessor
            List registryProcessors = new ArrayList<>();
            // 遍历所有参数传递进来的BeanFactoryPostProcessor(没有作为bean注册在容器中)
            // 将所有参数传入的BeanFactoryPostProcessor分为两组:
            // BeanDefinitionRegistryPostProcessor->postProcessBeanDefinitionRegistry
            // 常规的BeanFactoryPostProcessor只做记录不做处理
            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
            List currentRegistryProcessors = new ArrayList<>();

            // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
            // 首先,激活实现了PriorityOrdered接口的BeanDefinitionRegistryPostProcessors
            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);
            // 按顺序执行BeanDefinitionRegistryPostProcessors
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            currentRegistryProcessors.clear();

            // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
            // 其次,对实现了Ordered接口的BeanDefinitionRegistryPostProcessors进行调用
            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);
            currentRegistryProcessors.clear();

            // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
            // 最后执行没有实现上述两个接口的BeanDefinitionRegistryPostProcessors
            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);
                currentRegistryProcessors.clear();
            }

            // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
            // 现在,调用到目前为止已处理的所有处理器的postProcessBeanFactory回调
            // 由于BeanDefinitionRegistryPostProcessors继承自BeanFactoryPostProcessor,所以也会调用其
            // postProcessBeanFactory()的方法
            invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
            invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
        }

        else {
            // Invoke factory processors registered with the context instance.
            // 调用在上下文实例中注册的BeanFactoryPostProcessors,如果都是常规的BeanFactoryPostProcessor会执行这个
            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 priorityOrderedPostProcessors = new ArrayList<>();
        List orderedPostProcessorNames = new ArrayList<>();
        List 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 orderedPostProcessors = new ArrayList<>();
        for (String postProcessorName : orderedPostProcessorNames) {
            orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
        }
        sortPostProcessors(orderedPostProcessors, beanFactory);
        invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

        // Finally, invoke all other BeanFactoryPostProcessors.
        List nonOrderedPostProcessors = new ArrayList<>();
        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();
    }

很长的篇幅,其实这里主要是做激活BeanFactoryPostProcessors的操作.值得一提的是,Spring会按照@PriorityOrderOrder来执行BeanFactoryPostProcessors.

internalConfigurationAnnotationProcessor

Spring内置的BeanFactoryRegistryPostProcessor,通过以下的语句从DefaultListableFactory中获取到的postProcessorNames可以看到. 接下来通过getBean将该BeanFactoryRegistryPostProcessor加入到currentRegistryProcessors中进行激活。

内置的后置处理器

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);
// 按顺序执行BeanDefinitionRegistryPostProcessors
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
  • PostProcessorRegistrationDelegate#invokeBeanDefinitionRegistryPostProcessors

这里将收集到的BeanDefinitionRegistryPostProcessors进行循环激活,并传入容器进行注册.

    private static void invokeBeanDefinitionRegistryPostProcessors(
            Collection postProcessors, BeanDefinitionRegistry registry) {

        for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
            postProcessor.postProcessBeanDefinitionRegistry(registry);
        }
    }
  • ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry

为当前postProcessBeanDefinitionRegistry生成一个注册表id,防止二次执行,随后进行配置类的解析.通常为@Configuration所注释的类.

    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
        // 注册表id
        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);
    }
  • ConfigurationClassPostProcessor#processConfigBeanDefinitions

又是一段很长的逻辑,我们抓住重点分析.
首先在register()方法中Spring已经将配置类进行了注册,那么接下来Spring会对该配置类做一些检测。
在进行完资源环境的加载后,Spring根据当前参数new了一个ConfigurationClassParser,用以解析每一个被@Configuration所注解的类.
最后调用parser.parse(candidates);来解析配置类。

配置类
    public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
        List configCandidates = new ArrayList<>();
        // 获取当前注册器中的候选BeanDefinitionNames
        String[] candidateNames = registry.getBeanDefinitionNames();

        for (String beanName : candidateNames) {
            BeanDefinition beanDef = registry.getBeanDefinition(beanName);
            // Full和Lite模式的配置类
            if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) ||
                    ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
                }
            }
            //检查给定的bean定义是否适合配置类(或在配置/组件类中声明的嵌套组件类,也要自动注册),并进行相应标记。
            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
        // 根据@Order的顺序对BeanDefinition列表进行排序
        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
        // 检测通过封闭的应用程序上下文提供的任何自定义bean名称生成策略
        // 由于传入的是DefaultLitableFactory,它是SingletonBeanRegistry的子类,因此会执行这段逻辑
        SingletonBeanRegistry sbr = null;
        if (registry instanceof SingletonBeanRegistry) {
            sbr = (SingletonBeanRegistry) registry;
            if (!this.localBeanNameGeneratorSet) {
                BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(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
        // 解析每一个@Configuration的class,resourceLoader为注解容器,registry为DefaultListableFactory
        ConfigurationClassParser parser = new ConfigurationClassParser(
                this.metadataReaderFactory, this.problemReporter, this.environment,
                this.resourceLoader, this.componentScanBeanNameGenerator, registry);

        Set candidates = new LinkedHashSet<>(configCandidates);
        Set alreadyParsed = new HashSet<>(configCandidates.size());
        do {
            // 解析BeanDefinition,一般解析的是配置类
            parser.parse(candidates);
            parser.validate();

            Set 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);

            candidates.clear();
            if (registry.getBeanDefinitionCount() > candidateNames.length) {
                String[] newCandidateNames = registry.getBeanDefinitionNames();
                Set oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
                Set 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();
        }
    }
  • ConfigurationClassParser#parse(org.springframework.core.type.AnnotationMetadata, java.lang.String)
    // 解析配置类
    protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {
        processConfigurationClass(new ConfigurationClass(metadata, beanName));
    }
  • ConfigurationClassParser#processConfigurationClass

关注sourceClass = doProcessConfigurationClass(configClass, sourceClass);这段代码,开始真正解析配置类了.

    protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
        // 根据@Condition的条件来判断是否需要跳过
        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);
        do {
            sourceClass = doProcessConfigurationClass(configClass, sourceClass);
        }
        while (sourceClass != null);

        this.configurationClasses.put(configClass, configClass);
    }
  • #doProcessConfigurationClass

调用ComponentScanAnnotationParser.parse(AnnotationAttributes componentScan, final String declaringClass)完成组件扫描.

componentScan

    protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
            throws IOException {

        if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
            // Recursively process any member (nested) classes first
            processMemberClasses(configClass, sourceClass);
        }

        // Process any @PropertySource annotations
        for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
                sourceClass.getMetadata(), PropertySources.class,
                org.springframework.context.annotation.PropertySource.class)) {
            if (this.environment instanceof ConfigurableEnvironment) {
                processPropertySource(propertySource);
            }
            else {
                logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
                        "]. Reason: Environment must implement ConfigurableEnvironment");
            }
        }

        // Process any @ComponentScan annotations
        Set componentScans = AnnotationConfigUtils.attributesForRepeatable(
                sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
        if (!componentScans.isEmpty() &&
                !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
            // 循环componentScan实例
            for (AnnotationAttributes componentScan : componentScans) {
                // The config class is annotated with @ComponentScan -> perform the scan immediately
                Set scannedBeanDefinitions =
                        this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
                // Check the set of scanned definitions for any further config classes and parse recursively if needed
                for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
                    BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
                    if (bdCand == null) {
                        bdCand = holder.getBeanDefinition();
                    }
                    if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
                        parse(bdCand.getBeanClassName(), holder.getBeanName());
                    }
                }
            }
        }

        // Process any @Import annotations
        processImports(configClass, sourceClass, getImports(sourceClass), true);

        // Process any @ImportResource annotations
        AnnotationAttributes importResource =
                AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
        if (importResource != null) {
            String[] resources = importResource.getStringArray("locations");
            Class readerClass = importResource.getClass("reader");
            for (String resource : resources) {
                String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
                configClass.addImportedResource(resolvedResource, readerClass);
            }
        }

        // Process individual @Bean methods
        Set beanMethods = retrieveBeanMethodMetadata(sourceClass);
        for (MethodMetadata methodMetadata : beanMethods) {
            configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
        }

        // Process default methods on interfaces
        processInterfaces(configClass, sourceClass);

        // Process superclass, if any
        if (sourceClass.getMetadata().hasSuperClass()) {
            String superclass = sourceClass.getMetadata().getSuperClassName();
            if (superclass != null && !superclass.startsWith("java") &&
                    !this.knownSuperclasses.containsKey(superclass)) {
                this.knownSuperclasses.put(superclass, configClass);
                // Superclass found, return its annotation metadata and recurse
                return sourceClass.getSuperClass();
            }
        }

        // No superclass -> processing is complete
        return null;
    }
  • ComponentScanAnnotationParser#parse

解析basePackage,然后执行doScan();

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

        Class 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 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 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));
    }
  • ClassPathBeanDefinitionScanner#doScan

其中核心方法为->findCandidateComponents.它负责扫描到basePakckage路径下的Class,进而装配一个BeanDefinitionHolder的Set集合。
registerBeanDefinition(definitionHolder, this.registry);执行注册逻辑,到了这里与XML一致。

    protected Set doScan(String... basePackages) {
        Assert.notEmpty(basePackages, "At least one base package must be specified");
        Set beanDefinitions = new LinkedHashSet<>();
        for (String basePackage : basePackages) {
            // 根据basePackage生成候选的BeanDefinition集合
            Set 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);
                if (candidate instanceof AbstractBeanDefinition) {
                    postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
                }
                if (candidate instanceof AnnotatedBeanDefinition) {
                    AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
                }
                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;
    }
  • ClassPathScanningCandidateComponentProvider#scanCandidateComponents

可见,这里将basePackage解析成符合ant风格的表达式,然后再用ResourceLoader进行扫描获取Resource.再通过MetadataReader来读取类注解信息,然后装配到一个Set集合中,集合中装载的是每个BeanDefinition

    private Set scanCandidateComponents(String basePackage) {
        Set candidates = new LinkedHashSet<>();
        try {
            // 将basePackage中的.替换成/。举个例子: com.xjm->classpath*:com/xim/**/*.class
            String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
                    resolveBasePackage(basePackage) + '/' + this.resourcePattern;
            // 获取资源
            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->类和注解的元信息读取方法
                        MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource);
                        // excludeFilters和includeFilters决定
                        if (isCandidateComponent(metadataReader)) {
                            ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
                            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;
    }

总体流程

流程

总结

  • 注解容器的BeanDefinition较为特殊,包含类的注解元信息。
  • 组件扫描往往基于一个配置类进行资源定位,使用@ComponentScan()可以指定basePackage.
  • 容器先为配置类进行注册,随后在refresh()中对BeanDefinitionRegistryPostProcessor进行激活,这是组件扫描的入口
  • 组件扫描通过将basePackage进行路径转换,随后用ResourceLoader进行资源定位加载Resources.最后通过AnnotationTypeFilter@Component和其派生注解标注的类过滤出需要注册的Class文件。最后装载到一个装载BeanDefinition的Set集合.
  • 注解的BeanDefinition和XML的BeanDefinition注册流程入口皆为:BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, registry);

你可能感兴趣的:([Spring]基于注解的AnnotationConfigApplicationContext组件扫描过程)