美文网首页
ConfigurationClassPostProcessor

ConfigurationClassPostProcessor

作者: AndyWei123 | 来源:发表于2022-01-03 18:13 被阅读0次

    SpringApplication#refresh方法中,会去调用BeanDefinitionPostProcessor去进行预处理,这里有一个很重要的 processor 就是 ConfigurationClassPostProcessor , 他主要负责将 config bean 加载到 beaDefinitionMap 中。

    postProcessBeanDefinitionRegistry

    我们先来看一下代码:

    @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);
        }
    

    主要做了两件事情:
    1、生成当前 registry 的 id,然后到 registriesPostProcessedregistriesPostProcessed 中查找,是否存在,主要作用是去重。
    2、假如没有重复调用 processConfigBeanDefinitions 去加载。

    processConfigBeanDefinitions

    public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
            List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
    // 获取已经注册的 bean 名称,这里一般是我们的启动 Application 类。
            String[] candidateNames = registry.getBeanDefinitionNames();
    
            for (String beanName : candidateNames) {
                BeanDefinition beanDef = registry.getBeanDefinition(beanName);
    // 假如 beanDefinition 中的 ConfigurationClass 属性为 full 或者 lite 那代表已经解析过了,跳过。
                if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
                    }
                }
    // 判断当前类是否是 config 类,假如是就加入到 configCandidates 中。
                else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
                    configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
                }
            }
    // 假如 configCandidates 为空就返回
            // Return immediately if no @Configuration classes were found
            if (configCandidates.isEmpty()) {
                return;
            }
    
            // Sort by previously determined @Order value, if applicable
    // 对 configCandidates 使用 @Order 注解进行排序
            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) {
    // 设置 beanNameGenerator
                        this.componentScanBeanNameGenerator = generator;
                        this.importBeanNameGenerator = generator;
                    }
                }
            }
    
            if (this.environment == null) {
                this.environment = new StandardEnvironment();
            }
    
            // Parse each @Configuration class
    //实例化 ConfigurationClassParser 为后续解析准备。
            ConfigurationClassParser parser = new ConfigurationClassParser(
                    this.metadataReaderFactory, this.problemReporter, this.environment,
                    this.resourceLoader, this.componentScanBeanNameGenerator, registry);
    // 初始话 candidates 和 alreadyParsed 两个集合
            Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
            Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
            do {
    // 进行解析
                parser.parse(candidates);
                parser.validate();
    // 获取解析到的 ConfigurationClass
                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());
                }
    // 加载 ConfigurationClass 的 beanDefinition
                this.reader.loadBeanDefinitions(configClasses);
    // 添加到 ConfigurationClass 中。
                alreadyParsed.addAll(configClasses);
    
                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();
            }
        }
    

    主要做了如下7件事情:
    1、获取已经注册的bean名称进行遍历:
    2、对configCandidates 进行 排序,按照@Order 配置的值进行排序。
    3、如果BeanDefinitionRegistry 是SingletonBeanRegistry 子类的话,将registry强转为SingletonBeanRegistry。
    4、实例化ConfigurationClassParser 为了解析各个配置类.实例化2个set,candidates 用于将之前加入的configCandidates 进行去重,alreadyParsed 用于判断是否处理过。
    5、进行解析。
    6、如果SingletonBeanRegistry 不包含org.springframework.context.annotation.ConfigurationClassPostProcessor.importRegistry,则注册一个,bean 为 ImportRegistry. 一般都会进行注册的。
    7、清除缓存。
    我们先来看一下判断该 bean 是否为 configClass 的方法。

    ConfigurationClassUtils#checkConfigurationClassCandidate

    public static boolean checkConfigurationClassCandidate(
                BeanDefinition beanDef, MetadataReaderFactory metadataReaderFactory) {
    // 获取类名,假如不存在则返回。
            String className = beanDef.getBeanClassName();
            if (className == null || beanDef.getFactoryMethodName() != null) {
                return false;
            }
    // 获取 AnnotationMetadata
            AnnotationMetadata metadata;
            if (beanDef instanceof AnnotatedBeanDefinition &&
                    className.equals(((AnnotatedBeanDefinition) beanDef).getMetadata().getClassName())) {
                // Can reuse the pre-parsed metadata from the given BeanDefinition...
    // 检查是否可以是 AnnotatedBeanDefinition ,是就直接从 BeanDefinition 中获取
                metadata = ((AnnotatedBeanDefinition) beanDef).getMetadata();
            }
            else if (beanDef instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) beanDef).hasBeanClass()) {
                // Check already loaded Class if present...
                // since we possibly can't even load the class file for this Class.
    // 如果BeanDefinition 是 AnnotatedBeanDefinition的实例,并且beanDef 有 beanClass 属性存在没有则实例化StandardAnnotationMetadata
                Class<?> beanClass = ((AbstractBeanDefinition) beanDef).getBeanClass();
                if (BeanFactoryPostProcessor.class.isAssignableFrom(beanClass) ||
                        BeanPostProcessor.class.isAssignableFrom(beanClass) ||
                        AopInfrastructureBean.class.isAssignableFrom(beanClass) ||
                        EventListenerFactory.class.isAssignableFrom(beanClass)) {
                    return false;
                }
                metadata = AnnotationMetadata.introspect(beanClass);
            }
            else {
                try {
    // 否则 通过MetadataReaderFactory 中的MetadataReader 进行读取
                    MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(className);
                    metadata = metadataReader.getAnnotationMetadata();
                }
                catch (IOException ex) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Could not find class file for introspecting configuration annotations: " +
                                className, ex);
                    }
                    return false;
                }
            }
    // 如果存在Configuration 注解,则为BeanDefinition 设置configurationClass属性为full
            Map<String, Object> config = metadata.getAnnotationAttributes(Configuration.class.getName());
            if (config != null && !Boolean.FALSE.equals(config.get("proxyBeanMethods"))) {
                beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);
            }
    // 如果AnnotationMetadata 中有Component,ComponentScan,Import,ImportResource 注解中的任意一个,或者存在 被@bean 注解的方法,则返回true
            else if (config != null || isConfigurationCandidate(metadata)) {
                beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);
            }
            else {
                return false;
            }
    
            // It's a full or lite configuration candidate... Let's determine the order value, if any.
            Integer order = getOrder(metadata);
            if (order != null) {
                beanDef.setAttribute(ORDER_ATTRIBUTE, order);
            }
    
            return true;
        }
    

    详细的内容都行卸载注释中了,其实主要是对该类的注解进行判断。

    ConfigurationClassParser#parse

    public void parse(Set<BeanDefinitionHolder> configCandidates) {
            for (BeanDefinitionHolder holder : configCandidates) {
                BeanDefinition bd = holder.getBeanDefinition();
                try {
                    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();
        }
    

    其主要做了两件事情:
    1、遍历configCandidates ,进行处理.根据BeanDefinition 的类型 做不同的处理,一般都会调用ConfigurationClassParser#parse 进行解析。
    2、处理ImportSelect。
    我们先来看一下第一步:

    ConfigurationClassParser#parse
    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);
        }
    

    主要做如下4件事情:
    1、调用 shouldSkip 方法来判断该 configClass 是否需要 跳过。
    2、处理Imported 的情况。
    3、递归调用进行解析。
    4、添加到configurationClasses中。
    我们先来看一下 shouldSkip 方法:

    public boolean shouldSkip(@Nullable AnnotatedTypeMetadata metadata, @Nullable ConfigurationPhase phase) {
            if (metadata == null || !metadata.isAnnotated(Conditional.class.getName())) {
                return false;
            }
    
            if (phase == null) {
                if (metadata instanceof AnnotationMetadata &&
                        ConfigurationClassUtils.isConfigurationCandidate((AnnotationMetadata) metadata)) {
                    return shouldSkip(metadata, ConfigurationPhase.PARSE_CONFIGURATION);
                }
                return shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN);
            }
    
            List<Condition> conditions = new ArrayList<>();
            for (String[] conditionClasses : getConditionClasses(metadata)) {
                for (String conditionClass : conditionClasses) {
                    Condition condition = getCondition(conditionClass, this.context.getClassLoader());
                    conditions.add(condition);
                }
            }
    
            AnnotationAwareOrderComparator.sort(conditions);
    
            for (Condition condition : conditions) {
                ConfigurationPhase requiredPhase = null;
                if (condition instanceof ConfigurationCondition) {
                    requiredPhase = ((ConfigurationCondition) condition).getConfigurationPhase();
                }
                if ((requiredPhase == null || requiredPhase == phase) && !condition.matches(this.context, metadata)) {
                    return true;
                }
            }
    
            return false;
        }
    

    主要做4件事情:
    1、判断该类是否被 Condition 注解修饰,假如没有就直接返回。
    2、如果参数中沒有设置条件注解的生效阶段
    (1)、是配置类的话直接使用PARSE_CONFIGURATION阶段,递归调用shouldSkip 进行判断。
    (2)、否则使用REGISTER_BEAN阶段,递归调用shouldSkip 进行判断。
    3、获取配置类的条件注解得到条件数据,并添加到集合中.
    4、遍历conditions,进行判断,如果阶段不满足条件的话,返回true并跳过这个bean的解析。
    接下来我们看一下真正解析的步骤:

    protected final SourceClass doProcessConfigurationClass(
                ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)
                throws IOException {
    
            if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
                // Recursively process any member (nested) classes first
                processMemberClasses(configClass, sourceClass, filter);
            }
    
            // 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<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
                    sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
            if (!componentScans.isEmpty() &&
                    !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
                for (AnnotationAttributes componentScan : componentScans) {
                    // The config class is annotated with @ComponentScan -> perform the scan immediately
                    Set<BeanDefinitionHolder> 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), filter, true);
    
            // Process any @ImportResource annotations
            AnnotationAttributes importResource =
                    AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
            if (importResource != null) {
                String[] resources = importResource.getStringArray("locations");
                Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
                for (String resource : resources) {
                    String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
                    configClass.addImportedResource(resolvedResource, readerClass);
                }
            }
    
            // Process individual @Bean methods
            Set<MethodMetadata> 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;
        }
    

    主要做了如下8件事情:
    1、如果该类使用 @Component 注解,调用 processMemberClasses 方法,其主要作用是将类放到 importStack 中,并且判断是否有循环依赖度问题。
    2、处理@PropertySource.通过遍历该类中的@PropertySource的注解,如果该类中的environment是ConfigurableEnvironment 子类的话,则调用processPropertySource进行处理。
    3、处理@ComponentScan,通过遍历该类上的@ComponentScan 注解,并使用 conditionEvaluator.shouldSkip 进行判断是否需要跳过。没有就通过ComponentScanAnnotationParser#parse方法进行扫描:

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

    1、初始化 ClassPathBeanDefinitionScanner。
    2、为 ClassPathBeanDefinitionScanner 设置 nameGenerator、scopedProxy、scopeResolver、includeFilters 和 excludeFilters
    3、调用 scanner.doScan 方法,进行扫描:

    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) {
                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);
                    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;
        }
    

    1 、遍历basePackages,通过findCandidateComponents方法扫描basePackage路径下的java文件。
    2、假如存在,就遍历这路径上的类:
    (1)解析 scope属性。
    (2)生成 name 属性
    (3)检查当前bean是否已经注册,如果没有注册的话,则生成 BeanDefinitionHolder,并添加到 添加到beanDefinitions中
    (4)向BeanDefinitionRegistry进行注册。
    4、处理@Import 注解

    private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,
                Collection<SourceClass> importCandidates, Predicate<String> exclusionFilter,
                boolean checkForCircularImports) {
    // 假如 importCandidates 为空,就直接返回
            if (importCandidates.isEmpty()) {
                return;
            }
    // 检查循环依赖问题,
            if (checkForCircularImports && isChainedImportOnStack(configClass)) {
                this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
            }
            else {
                this.importStack.push(configClass);
                try {
    // 如果没有循环依赖问题,就遍历出路。
                    for (SourceClass candidate : importCandidates) {
                        if (candidate.isAssignable(ImportSelector.class)) {
                            // Candidate class is an ImportSelector -> delegate to it to determine imports
                            Class<?> candidateClass = candidate.loadClass();
                            ImportSelector selector = ParserStrategyUtils.instantiateClass(candidateClass, ImportSelector.class,
                                    this.environment, this.resourceLoader, this.registry);
                            Predicate<String> selectorFilter = selector.getExclusionFilter();
                            if (selectorFilter != null) {
                                exclusionFilter = exclusionFilter.or(selectorFilter);
                            }
                            if (selector instanceof DeferredImportSelector) {
                                this.deferredImportSelectorHandler.handle(configClass, (DeferredImportSelector) selector);
                            }
                            else {
                                String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
                                Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames, exclusionFilter);
                                processImports(configClass, currentSourceClass, importSourceClasses, exclusionFilter, false);
                            }
                        }
                        else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) {
                            // Candidate class is an ImportBeanDefinitionRegistrar ->
                            // delegate to it to register additional bean definitions
                            Class<?> candidateClass = candidate.loadClass();
                            ImportBeanDefinitionRegistrar registrar =
                                    ParserStrategyUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class,
                                            this.environment, this.resourceLoader, this.registry);
                            configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
                        }
                        else {
                            // Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar ->
                            // process it as an @Configuration class
                            this.importStack.registerImport(
                                    currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
                            processConfigurationClass(candidate.asConfigClass(configClass), exclusionFilter);
                        }
                    }
                }
                catch (BeanDefinitionStoreException ex) {
                    throw ex;
                }
                catch (Throwable ex) {
                    throw new BeanDefinitionStoreException(
                            "Failed to process import candidates for configuration class [" +
                            configClass.getMetadata().getClassName() + "]", ex);
                }
                finally {
                    this.importStack.pop();
                }
            }
        }
    

    主要处理流程如下:
    1、判断 importCandidates 是否为空,假如不是就返回。
    2、对其进行循环依赖检查。
    3、将其加入到 importstack 中,然后依次遍历。
    (1)如果是importSelect 子类,就实例化 ImportSelector 对象,通过 ParserStrategyUtils#instantiateClass 方法。
    [1]设置 ImportSelector exclusionFilter 属性。
    [2]假如 selector 是 DeferredImportSelector 属性,就调用 deferredImportSelectorHandler#handle 方法。
    [3]假如不是最后调用 processImports 方法。
    (2) 如果该类是 ImportBeanDefinitionRegistrar的子类,,则实例化后,调用ParserStrategyUtils#invokeAwareMethods,添加到configClass中。
    (3)最后假如都不是就加入到importStack后调用processConfigurationClass 进行处理。

    5、处理 @ImportResource 注解,先重 config 类中查找是否存在该注解,假如存在,就获取其 location 属性,然后遍历 location 位置中的 bean,加入到 configClass 中的 ImportedResource。
    6、处理 @Bean 的方法,遍历 @Bean 的方法,并放到 configClass 的 BeanMethod 中。
    7、遍历 configClass 的所有接口的 @Bean 的方法,并放到 configClass 的 BeanMethod 中。
    8、如果存在父类的话,就将父类放到 knownSuperclasses 中,并返回,返回就类似于递归调用。否则返回 null。
    我们回到ConfigurationClassPostProcessor的processConfigBeanDefinitions方法中,接下来是调用 ConfigurationClassBeanDefinitionReader#loadBeanDefinitions 方法。

        public void loadBeanDefinitions(Set<ConfigurationClass> configurationModel) {
            TrackedConditionEvaluator trackedConditionEvaluator = new TrackedConditionEvaluator();
            for (ConfigurationClass configClass : configurationModel) {
                loadBeanDefinitionsForConfigurationClass(configClass, trackedConditionEvaluator);
            }
        }
    

    如上,主要做两件事情:
    1、实例化 TrackedConditionEvaluator;
    2、遍历configurationModel ,使用loadBeanDefinitionsForConfigurationClass 方法加载 BeanDefinition。
    loadBeanDefinitionsForConfigurationClass 方法如下:

    private void loadBeanDefinitionsForConfigurationClass(
                ConfigurationClass configClass, TrackedConditionEvaluator trackedConditionEvaluator) {
    
            if (trackedConditionEvaluator.shouldSkip(configClass)) {
                String beanName = configClass.getBeanName();
                if (StringUtils.hasLength(beanName) && this.registry.containsBeanDefinition(beanName)) {
                    this.registry.removeBeanDefinition(beanName);
                }
                this.importRegistry.removeImportingClass(configClass.getMetadata().getClassName());
                return;
            }
    
            if (configClass.isImported()) {
                registerBeanDefinitionForImportedConfigurationClass(configClass);
            }
            for (BeanMethod beanMethod : configClass.getBeanMethods()) {
                loadBeanDefinitionsForBeanMethod(beanMethod);
            }
    
            loadBeanDefinitionsFromImportedResources(configClass.getImportedResources());
            loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars());
        }
    

    主要做了如下几件事情:
    1、调用 trackedConditionEvaluator 来判断条件注解,是否需要跳过这个 config 类。如果需要,就将这个类从容器中移除,并且从 importRegistry 中移除。
    2、如果当前类中存在@Import 注解,调用 registerBeanDefinitionForImportedConfigurationClass 方法进行注册:

    private void registerBeanDefinitionForImportedConfigurationClass(ConfigurationClass configClass) {
            AnnotationMetadata metadata = configClass.getMetadata();
            AnnotatedGenericBeanDefinition configBeanDef = new AnnotatedGenericBeanDefinition(metadata);
    
            ScopeMetadata scopeMetadata = scopeMetadataResolver.resolveScopeMetadata(configBeanDef);
            configBeanDef.setScope(scopeMetadata.getScopeName());
            String configBeanName = this.importBeanNameGenerator.generateBeanName(configBeanDef, this.registry);
            AnnotationConfigUtils.processCommonDefinitionAnnotations(configBeanDef, metadata);
    
            BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(configBeanDef, configBeanName);
            definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
            this.registry.registerBeanDefinition(definitionHolder.getBeanName(), definitionHolder.getBeanDefinition());
            configClass.setBeanName(configBeanName);
    
            if (logger.isTraceEnabled()) {
                logger.trace("Registered bean definition for imported class '" + configBeanName + "'");
            }
        }
    

    主要做的事情如下:
    1、根据 configClass 的 AnnotatedGenericBeanDefinition 生成 BeanDefinition。
    2、对BeanDefinition 进行属性设置:

    1、解析 configClass的Scope。
    2、生成 bean 的 id。
    3、设置 bean 的一些属性,如 lazy 和 primary 等。

    回到上面 loadBeanDefinitionsForConfigurationClass 方法。
    3、遍历BeanMethods,依次对其调用loadBeanDefinitionsForBeanMethod进行注册。

    private void loadBeanDefinitionsForBeanMethod(BeanMethod beanMethod) {
    // 获取父的 configClass
            ConfigurationClass configClass = beanMethod.getConfigurationClass();
    // 获取 beanMethod 的 MethodMetadata 和 methodName
            MethodMetadata metadata = beanMethod.getMetadata();
            String methodName = metadata.getMethodName();
    // 判断是否需要跳过,假如 conditionEvaluator#shouldSkip 返回 TRUE ,就将其放入 skippedBeanMethods 中并返回。
            // Do we need to mark the bean as skipped by its condition?
            if (this.conditionEvaluator.shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN)) {
                configClass.skippedBeanMethods.add(methodName);
                return;
            }
    //  如果configClass的skippedBeanMethods包含该methodName的话,不进行处理,
            if (configClass.skippedBeanMethods.contains(methodName)) {
                return;
            }
    // 从@Bean 注解中获取 name 假如为空就将 methodName 作为 name
            AnnotationAttributes bean = AnnotationConfigUtils.attributesFor(metadata, Bean.class);
            Assert.state(bean != null, "No @Bean annotation attributes");
    // 
            // Consider name and any aliases
            List<String> names = new ArrayList<>(Arrays.asList(bean.getStringArray("name")));
            String beanName = (!names.isEmpty() ? names.remove(0) : methodName);
    // 为 bean 设置 alias
            // Register aliases even when overridden
            for (String alias : names) {
                this.registry.registerAlias(beanName, alias);
            }
    // 查看是否存在重复注册的场景
            // Has this effectively been overridden before (e.g. via XML)?
            if (isOverriddenByExistingDefinition(beanMethod, beanName)) {
                if (beanName.equals(beanMethod.getConfigurationClass().getBeanName())) {
                    throw new BeanDefinitionStoreException(beanMethod.getConfigurationClass().getResource().getDescription(),
                            beanName, "Bean name derived from @Bean method '" + beanMethod.getMetadata().getMethodName() +
                            "' clashes with bean name for containing configuration class; please make those names unique!");
                }
                return;
            }
    // 实例化 ConfigurationClassBeanDefinition
            ConfigurationClassBeanDefinition beanDef = new ConfigurationClassBeanDefinition(configClass, metadata, beanName);
            beanDef.setSource(this.sourceExtractor.extractSource(metadata, configClass.getResource()));
    // 如果是静态方法,则设置 setBeanClassName,
            if (metadata.isStatic()) {
                // static @Bean method
                if (configClass.getMetadata() instanceof StandardAnnotationMetadata) {
                    beanDef.setBeanClass(((StandardAnnotationMetadata) configClass.getMetadata()).getIntrospectedClass());
                }
                else {
                    beanDef.setBeanClassName(configClass.getMetadata().getClassName());
                }
                beanDef.setUniqueFactoryMethodName(methodName);
            }
            else {
                // instance @Bean method
    //  如果是实例方法的话,则将configClass的BeanName设置为FactoryBeanName,methodName设置为UniqueFactoryMethodName
                beanDef.setFactoryBeanName(configClass.getBeanName());
                beanDef.setUniqueFactoryMethodName(methodName);
            }
    
            if (metadata instanceof StandardMethodMetadata) {
                beanDef.setResolvedFactoryMethod(((StandardMethodMetadata) metadata).getIntrospectedMethod());
            }
    // 设置注入模式为构造器注入模式
            beanDef.setAutowireMode(AbstractBeanDefinition.AUTOWIRE_CONSTRUCTOR);
    // 设置skipRequiredCheck属性为true       beanDef.setAttribute(org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor.
                    SKIP_REQUIRED_CHECK_ATTRIBUTE, Boolean.TRUE);
    // 6.4 进行一些常用的属性设置
            AnnotationConfigUtils.processCommonDefinitionAnnotations(beanDef, metadata);
    
            Autowire autowire = bean.getEnum("autowire");
            if (autowire.isAutowire()) {
                beanDef.setAutowireMode(autowire.value());
            }
    
            boolean autowireCandidate = bean.getBoolean("autowireCandidate");
            if (!autowireCandidate) {
                beanDef.setAutowireCandidate(false);
            }
    // 设置 initMethod
            String initMethodName = bean.getString("initMethod");
            if (StringUtils.hasText(initMethodName)) {
                beanDef.setInitMethodName(initMethodName);
            }
    // 设置 destroyMethod
            String destroyMethodName = bean.getString("destroyMethod");
            beanDef.setDestroyMethodName(destroyMethodName);
    // 设置ScopedProxyMode
            // Consider scoping
            ScopedProxyMode proxyMode = ScopedProxyMode.NO;
            AnnotationAttributes attributes = AnnotationConfigUtils.attributesFor(metadata, Scope.class);
            if (attributes != null) {
                beanDef.setScope(attributes.getString("value"));
                proxyMode = attributes.getEnum("proxyMode");
                if (proxyMode == ScopedProxyMode.DEFAULT) {
                    proxyMode = ScopedProxyMode.NO;
                }
            }
    // 如果 ScopedProxyMode 为 NO 就生成代理
            // Replace the original bean definition with the target one, if necessary
            BeanDefinition beanDefToRegister = beanDef;
            if (proxyMode != ScopedProxyMode.NO) {
                BeanDefinitionHolder proxyDef = ScopedProxyCreator.createScopedProxy(
                        new BeanDefinitionHolder(beanDef, beanName), this.registry,
                        proxyMode == ScopedProxyMode.TARGET_CLASS);
                beanDefToRegister = new ConfigurationClassBeanDefinition(
                        (RootBeanDefinition) proxyDef.getBeanDefinition(), configClass, metadata, beanName);
            }
    
            if (logger.isTraceEnabled()) {
                logger.trace(String.format("Registering bean definition for @Bean method %s.%s()",
                        configClass.getMetadata().getClassName(), beanName));
            }
    // 注册
            this.registry.registerBeanDefinition(beanName, beanDefToRegister);
        }
    

    主要做了7件事情:
    1、获取 configClass 、Methodname 和 MethodMetadata 。
    2、判断是否需要跳过出来:
    (1)、调用 conditionEvaluator#shouldSkip 方法是否需要跳过,需要返回。
    (2)、查看 skippedBeanMethods 中是否包含该方法,有则返回。
    3、从 @Bean 注解中获取 name 假如为空就查找 methodName ,设置为 bean name。
    4、对 name 的别名进行注册。
    5、 实例化 ConfigurationClassBeanDefinition ,如果该方法是静态方法,设置该方法为工厂方法,否则如果是实例方法的话,则将configClass的BeanName设置为FactoryBeanName,methodName设置为UniqueFactoryMethodName,然后设置 initmethod 和 destroymethod ,最后设置 ScopedProxyMode 设置为 NO 并生成代理。
    6、 注册 Bean。

    4、处理 @ImportResource 注解,具体如下:

    private void loadBeanDefinitionsFromImportedResources(
                Map<String, Class<? extends BeanDefinitionReader>> importedResources) {
    
            Map<Class<?>, BeanDefinitionReader> readerInstanceCache = new HashMap<>();
    // 遍历所有的 importedResources
            importedResources.forEach((resource, readerClass) -> {
                // Default reader selection necessary?
    // 如果是 BeanDefinitionReader,就查看是否是 groovy 类,假如不是就使用 XmlBeanDefinitionReader 类
                if (BeanDefinitionReader.class == readerClass) {
                    if (StringUtils.endsWithIgnoreCase(resource, ".groovy")) {
                        // When clearly asking for Groovy, that's what they'll get...
                        readerClass = GroovyBeanDefinitionReader.class;
                    }
                    else {
                        // Primarily ".xml" files but for any other extension as well
                        readerClass = XmlBeanDefinitionReader.class;
                    }
                }
    // 尝试重 readerInstanceCache 读取 BeanDefinitionReader 假如没有就实例化。
                BeanDefinitionReader reader = readerInstanceCache.get(readerClass);
                if (reader == null) {
                    try {
                        // Instantiate the specified BeanDefinitionReader
                        reader = readerClass.getConstructor(BeanDefinitionRegistry.class).newInstance(this.registry);
                        // Delegate the current ResourceLoader to it if possible
                        if (reader instanceof AbstractBeanDefinitionReader) {
                            AbstractBeanDefinitionReader abdr = ((AbstractBeanDefinitionReader) reader);
                            abdr.setResourceLoader(this.resourceLoader);
                            abdr.setEnvironment(this.environment);
                        }
                        readerInstanceCache.put(readerClass, reader);
                    }
                    catch (Throwable ex) {
                        throw new IllegalStateException(
                                "Could not instantiate BeanDefinitionReader class [" + readerClass.getName() + "]");
                    }
                }
    // 加载 bean
                // TODO SPR-6310: qualify relative path locations as done in AbstractContextLoader.modifyLocations
                reader.loadBeanDefinitions(resource);
            });
        }
    

    主要做了四件事情:
    1、遍历所有的 importedResources 。
    2、选择 BeanDefinitionReader,假如是 groovy 类,就使用 GroovyBeanDefinitionReader 不是就使用 XmlBeanDefinitionReader
    3、尝试从readerInstanceCache中获取对应的BeanDefinitionReader,如果不存在,则实例化一个,然后放入到readerInstanceCache缓存中。
    4、调用 BeanDefinitionReader#loadBeanDefinitions 进行加载 bean。

    5、注册@Import注解中的ImportBeanDefinitionRegistrar接口的registerBeanDefinitions。

        private void loadBeanDefinitionsFromRegistrars(Map<ImportBeanDefinitionRegistrar, AnnotationMetadata> registrars) {
            registrars.forEach((registrar, metadata) ->
                    registrar.registerBeanDefinitions(metadata, this.registry, this.importBeanNameGenerator));
        }
    

    相关文章

      网友评论

          本文标题:ConfigurationClassPostProcessor

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