Spring系列之BeanDefinition

2020-12-16  本文已影响0人  just_like_you

BeanDefinition

AnnotatedBeanDefinition

注解相关Bean的定义信息

  1. 具有通用BeanDefinition
  2. 具有AnnotationMetadata(类和注解相关元信息)以及MethodMetadata(工厂方法元信息)
  3. AnnotationMetadata具有AnnotatedTypeMetadata,后者有包含了MergedAnnotations (MergedAnnotation的迭代器模式)

相关核心依赖类图如下,所以想深入了解注解驱动的元数据构造,则需要深入理解各个组件的作用,特别是MergedAnnotation

[图片上传失败...(image-32dd59-1608131856000)]

MergedAnnotation

见名知意,这个接口表示合并的注解元信息。为什么是合并的呢?因为注解可以通过元标注的方式实现类似Class继承的操作。

代码演示场景

//自定义注解声明
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Configuration
public @interface MyConfiguration {

    @AliasFor(annotation = Configuration.class)
    String value() default "";

    @AliasFor(annotation = Configuration.class)
    boolean proxyBeanMethods() default true;

}

//定义一个列声明自定义注解,扩展了@Configuration
@MyConfiguration(value = "z3", proxyBeanMethods = false)
public class MergedAnnotationDemo{}

判断是否存在相关API

在合并的元信息中判断某些注解是否存在

[图片上传失败...(image-c26b44-1608131856000)]

//注解依赖关系 MyConfiguration <- Configuration <- Component <- Indexed
//from静态方法用来构造合并的Annotations元信息
MergedAnnotations annotations = MergedAnnotations.from(MergedAnnotationDemo.class);
//1. 是否直接标注该注解,元标注的不算 ,这里 Indexed并不是直接标注在MyConfiguration上,所有返回false
displayApi("isDirectlyPresent", annotations.isDirectlyPresent(Indexed.class)); 
 //2. 是否元标注或者直接标志该注解,Indexed是MyConfiguration的元标注注解,返回true
displayApi("isPresent", annotations.isPresent(Indexed.class));
//3. 是否是元标注注解,Indexed是元标注注解 ,返回true
displayApi("isMetaPresent", annotations.get(Configuration.class).isMetaPresent());

//output
isDirectlyPresent  = false
isPresent  = true
isMetaPresent  = true

注解位置相关API

在合并注解元信息中找到指定注解和当前申明的AnnotatedElement的位置信息

//距离当前source(MergedAnnotationDemo.class)的位置信息
//1.Configuration有是元标注在MyConfiguration上,所有返回 1
displayApi("getDistance", annotations.get(Configuration.class).getDistance());
//2. 同理,MyConfiguration <- COnfiguration <- Component 
//  当前MergedAnnotation和指定注解的距离。直接标注为0,元标注为1,依次向上叠加
displayApi("getDistance", annotations.get(Component.class).getDistance());  //2
displayApi("getDistance", annotations.get(Indexed.class).getDistance()); //3
//javadoc中声明 是在stream中排序时使用,missing的annotation返回 -1 , 直接标注、元标注返回0
displayApi("getAggregateIndex", annotations.get(Target.class).getAggregateIndex());

//output
getDistance  = 1
getDistance  = 2
getDistance  = 3
getAggregateIndex  = 0

获取特定注解相关元信息API

在合并注解元信息中获取相关注解或者对象信息

//获取注解/元注解资源
 // 获取这个合并注解的源(无视层级)
displayApi("getSource", annotations.get(Indexed.class).getSource());
 //获取元标注的源注解信息
displayApi("getMetaSource", annotations.get(Indexed.class).getMetaSource().getType());
//获取distance为0的元信息 -> MyConfiguration
displayApi("getRoot", annotations.get(Indexed.class).getRoot().getType()); 
//获取所有元标注的Class信息
displayApi("getMetaTypes", annotations.get(Indexed.class).getMetaTypes()); 

//output
getSource  = class blog.spring.definition.MergedAnnotationDemo
getMetaSource  = interface org.springframework.stereotype.Component
getRoot  = interface blog.spring.anno.MyConfiguration
getMetaTypes  = [interface blog.spring.anno.MyConfiguration, interface org.springframework.context.annotation.Configuration, interface org.springframework.stereotype.Component, interface org.springframework.stereotype.Indexed]

获取注解属性相关API

//AnnotationAttribute相关API
//1. 判断某属性是否有默认值
displayApi("hasNonDefaultValue", annotations.get(Component.class).hasNonDefaultValue("value")); 
//2. 有获取注解属性的各种get方法,getString,getByte...
displayApi("getString", annotations.get(Configuration.class).getBoolean("proxyBeanMethods")); 
//3. 通用获取方法,可以指定类型信息
displayApi("getValue", annotations.get(Configuration.class).getValue("proxyBeanMethods",Boolean.class));

//4. 可以过滤有默认值的属性
displayApi("filterDefaultValues", annotations.get(Configuration.class).filterDefaultValues().getDefaultValue("proxyBeanMethods", Boolean.class));
//5. 通过Predicate进行属性名称过滤
displayApi("filterAttributes", annotations.get(Configuration.class).filterAttributes(s -> s.equals("z3")).getDefaultValue("proxyBeanMethods", Boolean.class)); //过滤属性名称
//6. withNonMergedAttributes()方法只能获取当前注解的属性信息,元标注的信息将不会被运用
displayApi("withNonMergedAttributes", annotations.get(Configuration.class).withNonMergedAttributes().getValue("value")); 
//6. 将注解属性信息转化成Map,AnnotationAttributes
displayApi("asAnnotationAttributes", annotations.get(MyConfiguration.class).asAnnotationAttributes().getString("value"));
displayApi("asMap", annotations.get(MyConfiguration.class).asMap(annotation -> new ConcurrentHashMap<>()).getClass().getSimpleName());

//7. 从合并注解元信息中获取合成的注解
Configuration configuration = annotations.get(Configuration.class).synthesize();

//8. 可以通过反射获取合并注解的相关属性,并可以在运行时动态修改注解属性值
System.out.println("before"+configuration.value());
displaySynthesizeInvocationHandler(configuration);
System.out.println("after"+configuration.value());

//解析合成的注解代理对象,注解代理信息
//默认注解会通过 AnnotationInvocationHandler进行代理处理
//Spring的MergedAnnotations则是通过 SynthesizedMergedAnnotationInvocationHandler来进行处理
//可以通过反射获取InvocationHandler中的被代理对象相关属性信息
private static void displaySynthesizeInvocationHandler(Configuration configuration) {
  InvocationHandler synthesizeInvocationHandler = Proxy.getInvocationHandler(configuration);
  ReflectionUtils.doWithFields(synthesizeInvocationHandler.getClass(), field -> {
    field.setAccessible(true);
    Object fieldVal = field.get(synthesizeInvocationHandler);
    //这里的valueCache是SynthesizedMergedAnnotationInvocationHandler代理中缓存的所有合并的注解属性信息
    if (field.getName().equals("valueCache")) {
      Map<String, Object> annotationFieldVal = (Map<String, Object>) fieldVal;
      annotationFieldVal.computeIfPresent("value", (k, v) -> v + "_proxy");
    }
  });
}

MergedAnnotations

是MergedAnnotation的迭代器模式,提供获取MergedAnnotations相关信息的工具类

[图片上传失败...(image-8d91f8-1608131856000)]

//from方法,构造成MergedAnnotations,可以从任意注解元素,并可以指定搜索方式和过滤来进行复杂注解信息查询
MergedAnnotations annotations = MergedAnnotations.from(MergedAnnotationDemo.class);
//可以通过get(String annotationType) 获取对应的MergedAnnotation信息。
MergedAnnotation annotation = MergedAnnotations.get(Configuration.class);

AnnotatedTypeMetadata

包含了MergedAnnotations,并提供了一些属性访问的工具方法,底层还是通过MergedAnnotations方法进行实现

[图片上传失败...(image-797eb4-1608131856000)]

ClassMetadata和AnnotationMetadata

这两个相比上面的底层注解API来说更加出场率高,分别代表了我们的类元信息和注解元信息。其中AnnotationMetadata继承了ClassMetadata , 通过ASM的放射来加载相关元信息。是AnnotatedBeanDefinition的重要元数据来源。

ClassMetadata

类信息描述,提供获取类名称,和一系列类描述信息,比如是否是接口,是否抽象类,可以获取成员的类型信息..

[图片上传失败...(image-4dd06d-1608131856000)]

AnnotationMetadata

包含注解的类元信息,是ClassMetadata的子类。并提供获取/判断注解类型相关辅助方法

//获取所有直接声明的Annotation Name
public default java.util.Set org.springframework.core.type.AnnotationMetadata.getAnnotationTypes()
//获取所有元注解
public default java.util.Set org.springframework.core.type.AnnotationMetadata.getMetaAnnotationTypes(java.lang.String)
//判断是否有直接声明的Annotation
public default boolean org.springframework.core.type.AnnotationMetadata.hasAnnotation(java.lang.String)
//  判断是否有元注解
public default boolean org.springframework.core.type.AnnotationMetadata.hasMetaAnnotation(java.lang.String)
// 判断是否有注解标注的方法
public default boolean org.springframework.core.type.AnnotationMetadata.hasAnnotatedMethods(java.lang.String)
  

AnnotatedBeanDefinition

注解类型的BeanDefinition,一般有两部分信息,一是通过类元信息AnnotationMetdata , 或者通过工厂方法(@Bean) MethodMetadata构成。其实现有一下几种

获取AnnotationMetadata的两种方式

使用类加载的方式

效率低,类加载需要使用ClassLoader加载字节码文件并在JVM中生成Class对象

AnnotationMetadata annotationMetadata = AnnotationMetadata.introspect(AnnotationMetadataDemo.class);

使用ASM直接读取字节码文件

直接使用字节码框架进行字节码文件读取,这里就是通过ASM的ClassReader来读取字节码资源

public class ClassReaderByASMDemo {

    public static void main(String[] args) throws IOException {
        //1. 创建MetadataReaderFactory
        CachingMetadataReaderFactory readerFactory = new CachingMetadataReaderFactory();
        //2. 使用ClassReader解析字节码获取MetadataReader对象
        MetadataReader metadataReader = readerFactory.getMetadataReader("blog.spring.definition.AnnotationMetadataDemo");
        //3. 从reader中获取注解元信息
        AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata();
        //4. 读取所有的注解属性信息
        System.out.println(annotationMetadata.getAllAnnotationAttributes(MyConfiguration.class.getName()));
    }
}

相关核心类图如下。

  1. 通过MetadataReaderFactory获取MetadataReader (SimpleMetadataReader)
  2. SimpleMetadataReader通过SimpleAnnotationMetadataReadingVisitor和ASMClassReader来加载字节码文件
  3. 返回AnnotationMetadata对象

[图片上传失败...(image-5230ac-1608131856000)]

AbstractBeanDefinition

是BeanDefinition的一个抽象实现类,提供了基本接口方法实现,包含了构造器参数,属性参数,class相关信息,是否懒加载,primary等等..

GenericBeanDefinition

提供了层次性的BeanDefinition实现。可以设置Parent BeanDefinition

RootBeanDefinition

表示一个最顶层的BeanDefinition,所有的BeanDefinition经过MergeBeanDefinition阶段之后都是这个类型。

BeanDefinition的构造方式

直接new相关的实现类

   public static void main(String[] args) {
                 //1. 直接new BeanDefinition相关实现类
            // 通用BeanDefinition
        GenericBeanDefinition beanDefinition = new GenericBeanDefinition();
            // 注解式BeanDefinition
        AnnotatedGenericBeanDefinition beanDefinitionWithAnnotated = new AnnotatedGenericBeanDefinition(User.class);
        beanDefinition.setBeanClassName(User.class.getName());
        MutablePropertyValues propertyValues = new MutablePropertyValues();
        propertyValues.add("name", "lazylittle");
        propertyValues.add("age", 11);
            //设置属性
        beanDefinition.setPropertyValues(propertyValues);
        beanDefinitionWithAnnotated.setPropertyValues(propertyValues);

        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
            //注册并查找
        beanFactory.registerBeanDefinition("user", beanDefinition);
        beanFactory.registerBeanDefinition("userWithAnnotated",beanDefinitionWithAnnotated);
        System.out.println(beanFactory.getBeansOfType( User.class));
    }

//output
{user=User(name=lazylittle, age=11), userWithAnnotated=User(name=lazylittle, age=11)}

使用BeanDefinitionBuilder进行构造

                //1. 使用BeanDefinitionBuilder进行构造
                AbstractBeanDefinition z3BeanDefinition = BeanDefinitionBuilder.rootBeanDefinition(User.class)
                .addPropertyValue("name", "z3")
                .addPropertyValue("age", 22)
                .getBeanDefinition();

        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
                //2. 使用工具类进行注册,底层就是调用BeanDefinitionRegistry#registerBeanDefinition()
        BeanDefinitionReaderUtils.registerBeanDefinition(new BeanDefinitionHolder(z3BeanDefinition, "userZ3"), beanFactory);
        System.out.println(beanFactory.getBeansOfType( User.class));

注册BeanDefinition的方式

命名式

BeanDefinitionRegistry/BeanDefinitionReaderUtils.registerBeanDefinition("user-1", BeanDefinitionBuilder.genericBeanDefinition(User.class).addPropertyValue("name", "z3").getBeanDefinition());

非命名式

BeanDefinitionReaderUtils.registerWithGeneratedName(
            AbstractBeanDefinition definition, BeanDefinitionRegistry registry);

Spring容器加载BeanDefinition源码解析

Spring 容器是通过 xxxBeanDefinitionReader类来进行相关元信息的加载

Xml文件

核心方法入口 : XmlBeanDefinitionReader#loadBeanDefinitions()

相关类图如下

https\://www.zzhujing.com/users/schema/users.xsd=spring/in/action/configuration/xml/user.xsd
protected void doRegisterBeanDefinitions(Element root) {
        //1. 创建Delegate
        BeanDefinitionParserDelegate parent = this.delegate;
        this.delegate = createDelegate(getReaderContext(), root, parent);

        if (this.delegate.isDefaultNamespace(root)) {
            String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
            if (StringUtils.hasText(profileSpec)) {
                String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
                        profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
                // We cannot use Profiles.of(...) since profile expressions are not supported
                // in XML config. See SPR-12458 for details.
                if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
                    if (logger.isDebugEnabled()) {
                        logger.debug("Skipped XML bean definition file due to specified profiles [" + profileSpec +
                                "] not matching: " + getReaderContext().getResource());
                    }
                    return;
                }
            }
        }
    
        preProcessXml(root);
    //2. 委派给BeanDefinitionParserDelegate进行解析
        parseBeanDefinitions(root, this.delegate);
        postProcessXml(root);

        this.delegate = parent;
    }
    public BeanDefinition parseCustomElement(Element ele, @Nullable BeanDefinition containingBd) {
        String namespaceUri = getNamespaceURI(ele);
        if (namespaceUri == null) {
            return null;
        }
    //根据名称空间的uri获取NamespaceHandler , spring.handlers中 k-v配置
        NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
        if (handler == null) {
            error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele);
            return null;
        }
    //获取BeanDefinitionParser进行解析
        return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
    }

其实上面的流程就是Spring的Extensible XML Authoring 扩展机制,我们常用的<aop:xxx>,<context:xx>都是这样加载的。

加载流程

  1. 加载Xml文件
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
            throws BeanDefinitionStoreException {

        try {
            //1. xml解析为Document对象
            Document doc = doLoadDocument(inputSource, resource);
            //2. 解析Docuemnt -> BeanDefinition
            int count = registerBeanDefinitions(doc, resource);
            if (logger.isDebugEnabled()) {
                logger.debug("Loaded " + count + " bean definitions from " + resource);
            }
            return count;
        }
  1. 判断是解析默认命名空间还是自定义
    protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
        //通过schema文件的名称空间url来判断是否是默认的名称空间,默认名称空间为 <bean>相关
        if (delegate.isDefaultNamespace(root)) {
            NodeList nl = root.getChildNodes();
            for (int i = 0; i < nl.getLength(); i++) {
                Node node = nl.item(i);
                if (node instanceof Element) {
                    Element ele = (Element) node;
                    if (delegate.isDefaultNamespace(ele)) {
                        parseDefaultElement(ele, delegate);
                    }
                    else {
            //2. 解析自定义标签
                        delegate.parseCustomElement(ele);
                    }
                }
            }
        }
    }
  1. 默认则解析对应标签并设置到BeanDefinition中
//1. 解析不同的默认标签
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
        if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) { //<import>
            importBeanDefinitionResource(ele);
        }
        else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) { //<alias>
            processAliasRegistration(ele);
        }
        else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) { //<bean>
            processBeanDefinition(ele, delegate);
        }
        else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) { //<beans>
            // recurse
            doRegisterBeanDefinitions(ele);
        }
    }
    //2. <bean>标签解析流程
    protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
    //2.1 依次读取<bean>里面的属性构造成BeanDefinitionHolder
        BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
        if (bdHolder != null) {
            bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
            try {
                //2.2 注册到IOC容器中
                BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
            }
        }
    }
  1. 自定义标签则要通过NamespaceHandlerResolver获取到NamespaceHandler,然后获取对应前缀的BeanDefinitionParser解析出BeanDefinition
//1. 解析自定义标签    
public BeanDefinition parseCustomElement(Element ele, @Nullable BeanDefinition containingBd) {
    //1.1 获取当前元素的命名空间uri
        String namespaceUri = getNamespaceURI(ele);
        if (namespaceUri == null) {
            return null;
        }
    //1.2 通过NamespaceHandlerResolver获取对应的spring.handlers中配置好的handler实现
        NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
        if (handler == null) {
            error("Unable to locate Spring NamespaceHandler for XML schema namespace [" + namespaceUri + "]", ele);
            return null;
        }
    //委派给BeanDefinitionParser进行解析
        return handler.parse(ele, new ParserContext(this.readerContext, this, containingBd));
    }

//2. 最后都使用BeanDefinitionRegistry注册到IOC中

注解方式

AnnotationBeanDefinitionReader#register()

相关类图如下:

[图片上传失败...(image-8f8a62-1608131856000)]

核心类作用
  1. AnnotationBeanDefinitionReader : 注解BeanDefinition解析注册上下文对象
  2. ConditionEvaluator : 条件注解计算器,用来处理@Conditional相关注解
  3. ScopeMetadata : Bean的Scope元信息,包含当前Bean的Scope和生成代理对象的模式
  4. BeanNameGenerator : Bean名称生成器
  5. AnnotatedGenericBeanDefinition : 通用注解Bean定义信息
处理过程
//定位到 AnnotatedBeanDefinitionReader#doRegisterBean()
private <T> void doRegisterBean(Class<T> beanClass, @Nullable String name,
            @Nullable Class<? extends Annotation>[] qualifiers, @Nullable Supplier<T> supplier,
            @Nullable BeanDefinitionCustomizer[] customizers) {
        //1. 创建BeanDefinition
        AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(beanClass);
    //2. 进行Conditional相关计算过滤
        if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
            return;
        }
        //3. 设置实例工厂有的话,supplier在Bean的实例化的时候会优先于构造方法实例化
        abd.setInstanceSupplier(supplier);
    //4. 解析Scope元信息
        ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
        abd.setScope(scopeMetadata.getScopeName());
    //5. 生成BeanName
        String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
        //6. 处理通用注解@Lazy ,@Primary ,@DepensOn...
        AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
        //..省略部分自定义扩展
        BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
    //7. 如果需要代理则会生成代理对象的BeanDefinition
        definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
    //8. 注册到IOC容器中
        BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
    }

ConfigurationClassPostProcessor,注解驱动核心处理类

该类是一个BeanDefinitionRegistryPostProcessor,在容器启动的时候会回调其后置处理器相关的方法,对Spring提供的一些列注解进行处理 , 比如模式注解@Component,以及其派生注解 , @Import,@PropertySource,@ComponentScan等等。

下面我们来进行详细的源码解析,过程比较复杂。还望能耐心的研读!入口为ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry)

    public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
        //1. 唯一性检测
        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);
    //2. 开始解析
        processConfigBeanDefinitions(registry);
    }

正式解析processConfigBeanDefinitions

public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
        List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
        String[] candidateNames = registry.getBeanDefinitionNames();
        //1. 从IOC中获取所有获选的beanNames
        for (String beanName : candidateNames) {
            BeanDefinition beanDef = registry.getBeanDefinition(beanName);
            //1.1 判断是否已经已经处理过了
            if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
                }
            }
            //1.2 判断是否是候选的Configuration Class (Component | ComponentScan | Import | ImportSource | Bean) , 若是Configuration且ProxyBeanMethod属性为true,设置属性ConfigurationClassPostProcessor.configurationClass 为full,表示后序该Configuration Class需要被CGLIB增强,其他如Component,Import等为lite.不会被增强
            else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
        //1.3 添加到候选配置中
                configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
            }
        }

        // 若候选的配置类为空则直接返回
        if (configCandidates.isEmpty()) {
            return;
        }
        //2. 根据sort排序好所有的候选Bean
        configCandidates.sort((bd1, bd2) -> {
            int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
            int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
            return Integer.compare(i1, i2);
        });

        //3. 探测BeanNameGenerator
        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;
                }
            }
        }
        //初始化Environment对象
        if (this.environment == null) {
            this.environment = new StandardEnvironment();
        }

        //4. 解析所有的ConfigurationClass
        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");

            //4.1 解析候选的BeanDefinition 为 Configuration Class
            parser.parse(candidates);
            parser.validate();
            //4.2 读取所有探测到的Configuration Class
            Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
            configClasses.removeAll(alreadyParsed);
            if (this.reader == null) {
                this.reader = new ConfigurationClassBeanDefinitionReader(
                        registry, this.sourceExtractor, this.resourceLoader, this.environment,
                        this.importBeanNameGenerator, parser.getImportRegistry());
            }
            //4.3 加载Configuration Class
            this.reader.loadBeanDefinitions(configClasses);
            //4.4 放入已经解析的set集合中
            alreadyParsed.addAll(configClasses);
            processConfig.tag("classCount", () -> String.valueOf(configClasses.size())).end();

            candidates.clear();
            //4.5 判断IOC容器中是否新增了Bean数量(即parse方法过程有没有新增Bean)
            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());
                }
                //4.6 将新增的候选beanName添加到候选集合中继续递归处理
                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());
        //5. 将ImportRegistry注册为spring bean ,为了支持ImportAware接口回调将ImportClass的注解元信息传入
        if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
            sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
        }
        //6. 清空ASM中字节码缓存
        if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
            ((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
        }
    }

核心步骤

其中最为核心的是ConfigurationClassParser#parse()将候选的BeanDefinition解析为ConfigurationClass , so go on!

    //ConfigurationClassParser#parse()  
public void parse(Set<BeanDefinitionHolder> configCandidates) {
        //1. 迭代所有候选的Configuration Class
        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);
            }
        }
        //2. 最后处理 DeferredImportSelector
        this.deferredImportSelectorHandler.process();
    }

上面的各种不同入参的parse()方法,最后都会走到processConfigurationClass(ConfigurationClass,Predicate<String>)

    protected void processConfigurationClass(ConfigurationClass configClass, Predicate<String> filter) throws IOException {
        //1. 条件注解(@Condtional)判断
        if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
            return;
        }
        //2. 缓存处理
        ConfigurationClass existingClass = this.configurationClasses.get(configClass);
        if (existingClass != null) {
            //2.1 若当前Configuration Class已经被处理过了,这里直接合并Import
            if (configClass.isImported()) {
                if (existingClass.isImported()) {
                    existingClass.mergeImportedBy(configClass);
                }
                return;
            }
            else {
                //2.2 移除之前处理过的Configuration Class
                this.configurationClasses.remove(configClass);
                this.knownSuperclasses.values().removeIf(configClass::equals);
            }
        }
        //3. (核心)递归解析Configuration Class
        // Recursively process the configuration class and its superclass hierarchy.
        SourceClass sourceClass = asSourceClass(configClass, filter);
        do {
            sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter);
        }
        while (sourceClass != null);
        //4. 将当前ConfigurationClass设置到全局变量configurationClasses
        this.configurationClasses.put(configClass, configClass);
    }

doProcessConfigurationClass()终于来到了核心注解的处理方法


protected final SourceClass doProcessConfigurationClass(
            ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)
            throws IOException {
        //1. 处理@Component
        if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
            //1.1 将处理@Component的嵌套类。
            processMemberClasses(configClass, sourceClass, filter);
        }

        //2. 处理@PropertySource,会创建一个PropertySource并添加到Environment中
        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");
            }
        }

        //3. 处理ComponentScan以及其嵌套注解
        Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
                sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
        //3.1 如果有ComponentScan元信息,且 注册bean阶段的条件注解通过
        if (!componentScans.isEmpty() &&
                !this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
            for (AnnotationAttributes componentScan : componentScans) {
                //解析ComponentScan注解并直接进行scan扫描相关Bean然后注册到容器中
                Set<BeanDefinitionHolder> scannedBeanDefinitions =
                        this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());

                for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
                    BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
                    if (bdCand == null) {
                        bdCand = holder.getBeanDefinition();
                    }
         //3.2 若扫描的BeanDefinition中有嵌套的Configuration Class则递归处理
                    if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
                        parse(bdCand.getBeanClassName(), holder.getBeanName());
                    }
                }
            }
        }

        //4. 处理@Import注解
        processImports(configClass, sourceClass, getImports(sourceClass), filter, true);

        //5. 处理@ImportResource
        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);
            }
        }

        //6. 处理@Bean
        Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
        for (MethodMetadata methodMetadata : beanMethods) {
            configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
        }

        // Process default methods on interfaces
        //7. 处理接口中的@Bean方法 (java8中的 default方法)
        processInterfaces(configClass, sourceClass);

        //8. 递归处理父类
        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;
    }

其中解析到这里大概流程就结束了。相关细节都大同小异。下面我们分布来看各个注解都是如何解析的

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

    private void processMemberClasses(ConfigurationClass configClass, SourceClass sourceClass,
            Predicate<String> filter) throws IOException {
        //1. 获取所有的内置类
        Collection<SourceClass> memberClasses = sourceClass.getMemberClasses();
        if (!memberClasses.isEmpty()) {
            List<SourceClass> candidates = new ArrayList<>(memberClasses.size());
            for (SourceClass memberClass : memberClasses) {
                if (ConfigurationClassUtils.isConfigurationCandidate(memberClass.getMetadata()) &&
                        !memberClass.getMetadata().getClassName().equals(configClass.getMetadata().getClassName())) {
                    candidates.add(memberClass);
                }
            }
            OrderComparator.sort(candidates);
            for (SourceClass candidate : candidates) {
                //3. 若当前Import栈中有了这个Configuration Class则出现循环导入!记录异常
                if (this.importStack.contains(configClass)) {
                    this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
                }
                else {
                    this.importStack.push(configClass);
                    try {
                        //2. 递归处理内置类
                        processConfigurationClass(candidate.asConfigClass(configClass), filter);
                    }
                    finally {
                        this.importStack.pop();
                    }
                }
            }
        }
    }
        //2. 处理@PropertySource,会创建一个PropertySource并添加到Environment中
        for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
                sourceClass.getMetadata(), PropertySources.class,
                org.springframework.context.annotation.PropertySource.class)) {
            if (this.environment instanceof ConfigurableEnvironment) {
                processPropertySource(propertySource);
            }
        }

    private void processPropertySource(AnnotationAttributes propertySource) throws IOException {
    //1. 解析PropertySource相关属性元信息,从AnnotatioAttributes中获取
        String name = propertySource.getString("name");
        if (!StringUtils.hasLength(name)) {
            name = null;
        }
        String encoding = propertySource.getString("encoding");
        if (!StringUtils.hasLength(encoding)) {
            encoding = null;
        }
        String[] locations = propertySource.getStringArray("value");
        Assert.isTrue(locations.length > 0, "At least one @PropertySource(value) location is required");
        boolean ignoreResourceNotFound = propertySource.getBoolean("ignoreResourceNotFound");

        Class<? extends PropertySourceFactory> factoryClass = propertySource.getClass("factory");
        PropertySourceFactory factory = (factoryClass == PropertySourceFactory.class ?
                DEFAULT_PROPERTY_SOURCE_FACTORY : BeanUtils.instantiateClass(factoryClass));
        //2. 迭代location并获取资源构造成PropertySource属性源
        for (String location : locations) {
            try {
                String resolvedLocation = this.environment.resolveRequiredPlaceholders(location);
                Resource resource = this.resourceLoader.getResource(resolvedLocation);
                addPropertySource(factory.createPropertySource(name, new EncodedResource(resource, encoding)));
            }
            catch (IllegalArgumentException | FileNotFoundException | UnknownHostException | SocketException ex) {
                // Placeholders not resolvable or resource not found when trying to open it
                if (ignoreResourceNotFound) {
                    if (logger.isInfoEnabled()) {
                        logger.info("Properties location [" + location + "] not resolvable: " + ex.getMessage());
                    }
                }
                else {
                    throw ex;
                }
            }
        }
    }
        //3. 处理ComponentScan以及其嵌套注解
        Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
                sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
        //3.1 如果有ComponentScan元信息,且 注册bean阶段的条件注解通过
        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());
                //3.2 若扫描的BeanDefinition中有嵌套的Configuration Class则递归处理
                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());
                    }
                }
            }
        }


//ComponentScanParser#parse()
public Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, final String declaringClass) {
        ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,
                componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);
        //省略大量读取ComponentScan属性元信息的代码..
    //1. 使用ClassPathBeanDefinitionScanner进行扫描候选的组件
        return scanner.doScan(StringUtils.toStringArray(basePackages));
}

    protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
        Assert.notEmpty(basePackages, "At least one base package must be specified");
        Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
        //1. 迭代扫描包
        for (String basePackage : basePackages) {
            //2. 查找包下的组件,直接通过ResourceLoader + ASM来读取字节码文件
            Set<BeanDefinition> candidates = findCandidateComponents(basePackage);

            //3. 迭代查找到的组件BeanDefinition
            for (BeanDefinition candidate : candidates) {

                //省略相关注解格外属性的处理..
        // 将扫描到的组件注册到IOC中
                    registerBeanDefinition(definitionHolder, this.registry);
                }
            }
        }
        return beanDefinitions;
    }
        //4. 处理@Import注解
        processImports(configClass, sourceClass, getImports(sourceClass), filter, true);


    private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,
            Collection<SourceClass> importCandidates, Predicate<String> exclusionFilter,
            boolean checkForCircularImports) {
            this.importStack.push(configClass);
            try {
                for (SourceClass candidate : importCandidates) {
                    //1.1 处理ImportSelector
                    if (candidate.isAssignable(ImportSelector.class)) {
                        //反射实例化ImportSelector并传入 Environment,ResourceLoader,BeanDefinitionReigstry
                        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) {
                            //暂存DeferredImportSelector,在最后面进行处理
                            this.deferredImportSelectorHandler.handle(configClass, (DeferredImportSelector) selector);
                        }
                        else {
                            String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
                            Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames, exclusionFilter);
                            //递归处理ImportSelector导入的配置类
                            processImports(configClass, currentSourceClass, importSourceClasses, exclusionFilter, false);
                        }
                    }
                    else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) {
                        Class<?> candidateClass = candidate.loadClass();
                        ImportBeanDefinitionRegistrar registrar =
                                ParserStrategyUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class,
                                        this.environment, this.resourceLoader, this.registry);
                        //处理ImportBeanDefinitionRegistrar
                        configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
                    }
                    else {
                        //处理其他类型的Configuration Class , 并将其添加到imports列表中
                        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();
            }
        }
    }

其中Import相关注解到后面都会被添加到ConfigurationClass相关的属性中缓存

final class ConfigurationClass {

    private final AnnotationMetadata metadata;

    private final Resource resource;

    @Nullable
    private String beanName;
    //记录所有@Import导入的Configuration Class
    private final Set<ConfigurationClass> importedBy = new LinkedHashSet<>(1);
    //记录所有解析@Bean生成的BeanMethod
    private final Set<BeanMethod> beanMethods = new LinkedHashSet<>();
    //记录所有@ImportResource (k->resource v->BeanDefinitionReader)
    private final Map<String, Class<? extends BeanDefinitionReader>> importedResources =
            new LinkedHashMap<>();
    //记录所有的ImportBeanDefinitionRegistrar (k -> ImportBeanDefinitionRegistrar ,v -> 声明类的注解元信息)
    private final Map<ImportBeanDefinitionRegistrar, AnnotationMetadata> importBeanDefinitionRegistrars =
            new LinkedHashMap<>();

最后使用ConfigurationClassBeanDefinitionReader#loadBeanDefinitionForConfiguratinoClass()完成Configuration Class的加载

    private void loadBeanDefinitionsForConfigurationClass(
            ConfigurationClass configClass, TrackedConditionEvaluator trackedConditionEvaluator) {
        //1. 条件注解过滤,若满足则移除该BeanDefinition
        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;
        }
        //注册Configuration Class
        if (configClass.isImported()) {
            registerBeanDefinitionForImportedConfigurationClass(configClass);
        }
        //注册BeanMethod
        for (BeanMethod beanMethod : configClass.getBeanMethods()) {
            loadBeanDefinitionsForBeanMethod(beanMethod);
        }
        //处理ImportResource,使用对应BeanDefinitionReader加载BeanDefinition
        loadBeanDefinitionsFromImportedResources(configClass.getImportedResources());
        //处理ImportBeanDefinitionRegistrar
        loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars());
    }

写在最后

由于ConfigurationClassPostProcessor相关解析代码比较复杂,但是其核心还是在相关元信息(AnnotationMetadata)的解析和BeanDefinition的解析(ClassPathBeanDefinitionScannerBeanDefinitionReader等)和注册方法(BeanDefinitionRegistry#reigsterBeanDefinition)使用,尤其是注解元信息,以及注解属性元信息(AnnotationAttributes)的相关api使用尤为的重要。建议好好看看上面AnnotatedBeanDefinition和更底层的MergedAnnotation相关api。

上一篇下一篇

猜你喜欢

热点阅读