Spring源码-----@Autowired标签解析以及AutowiredAnnotationBeanPostProcessor

 关于Autowired这是spring内部的自带的依赖注入的标签,可以用在构造函数、字段、setter方法或者配置方法上。作用是将我们需要注入的对象由Spring自动注入到目标对象中。Autowired标签的解析逻辑主要在AutowiredAnnotationBeanPostProcessor类中,而除了Autowired标签还有Value标签以及JSR-330规范的Inject标签的解析也在这个里面。下面进行分析。

1.AutowiredAnnotationBeanPostProcessor何时实例化的

1.传统的spring用xml的配置方式下的实例化

 这里要先说明一下,如果是传统的Spring的web.xml+spring.xml配置的形式来管理Bean的话,AutowiredAnnotationBeanPostProcessor是不会被实例化的。因为这个时候系统默认初始化的web上下文子类是XmlWebApplicationContext,关于为什么是这个类可以看Spring如何在Tomcat启动的时候启动的这篇文章,这里继续往下
XmlWebApplicationContext类中调用实现的loadBeanDefinitions方法的逻辑中并不会涉及到AnnotatedBeanDefinitionReader类(后面会讲到),而在AnnotatedBeanDefinitionReader中又与注册AutowiredAnnotationBeanPostProcessor类相关的步骤。
 如果就用xml配置bean却不允许用注解注入肯定是不行的,所以我们一般会在spring的xml文件中加入这一的标签

<context:annotation-config/>

或者

<context:component-scan>

 这里说明一下component-scan中有一个annotation-config属性这个属性默认是true表示开启注解配置。上面两个标签对呀的解析处理类不同,这里关于spring的xml文件解析就不再讲解了,可以参考前面的Spring源码解析——容器的基础XmlBeanFactory
等文章进行了解,这里直接介绍这两个标签的处理类

1. 处理<context:annotation-config/>AnnotationConfigBeanDefinitionParser

AnnotationConfigBeanDefinitionParser类是用来处理<context:annotation-config/>标签的,这个类中主要就是注册处理注解注入相关的类

    public BeanDefinition parse(Element element, ParserContext parserContext) {
        Object source = parserContext.extractSource(element);

        // 获取所有的注解注入相关的beanpostprocessor的bean定义
        Set<BeanDefinitionHolder> processorDefinitions =
                AnnotationConfigUtils.registerAnnotationConfigProcessors(parserContext.getRegistry(), source);

        //注册一个CompositeComponentDefinition,将xml的配置信息保存进去
        CompositeComponentDefinition compDefinition = new CompositeComponentDefinition(element.getTagName(), source);
        parserContext.pushContainingComponent(compDefinition);

        // 将上面获取的Bean保存到解析的上下文对象中
        for (BeanDefinitionHolder processorDefinition : processorDefinitions) {
            parserContext.registerComponent(new BeanComponentDefinition(processorDefinition));
        }

        //最后将保存的bean注册到复合组件。
        parserContext.popAndRegisterContainingComponent();

        return null;
    }

其中关键的步骤是AnnotationConfigUtils类的registerAnnotationConfigProcessors方法,这里后面一起说。

2. 处理<context:component-scan/>ComponentScanBeanDefinitionParser

ComponentScanBeanDefinitionParser的逻辑还是比较多的,因为继承了BeanDefinitionParser所以直接看对应的parse方法,关于BeanDefinitionParser可以看看前面的Spring源码解析——自定义标签的使用了解。这里看代码

    public BeanDefinition parse(Element element, ParserContext parserContext) {
              ......
        //注册组件
        registerComponents(parserContext.getReaderContext(), beanDefinitions, element);
        return null;
    }

&msp;代码中省略的部分前面代码省略,主要就是获取<context:component-scan/>base-package属性然后扫描并获取候选Bean并保存到BeanDefinitionHolder集合的对象中。这里主要看registerComponents方法。

    protected void registerComponents(
            XmlReaderContext readerContext, Set<BeanDefinitionHolder> beanDefinitions, Element element) {
              //获取<context:component-scan/>标签的源信息
        Object source = readerContext.extractSource(element);  
          //将上面的源信息保存包以<context:component-scan/>标签的tag为名称的CompositeComponentDefinition对象中
        CompositeComponentDefinition compositeDef = new CompositeComponentDefinition(element.getTagName(), source);
//将前面获取到的候选Bean以此丢到compositeDef中
        for (BeanDefinitionHolder beanDefHolder : beanDefinitions) {
            compositeDef.addNestedComponent(new BeanComponentDefinition(beanDefHolder));
        }

        
        boolean annotationConfig = true;
        if (element.hasAttribute(ANNOTATION_CONFIG_ATTRIBUTE)) {
            annotationConfig = Boolean.parseBoolean(element.getAttribute(ANNOTATION_CONFIG_ATTRIBUTE));
        }
//如果component-scan标签中包含annotation-config属性并且值为true,则调用AnnotationConfigUtils的registerAnnotationConfigProcessors将注解配置相关的postprocessor保存到compositeDef中
        if (annotationConfig) {
            Set<BeanDefinitionHolder> processorDefinitions =
                    AnnotationConfigUtils.registerAnnotationConfigProcessors(readerContext.getRegistry(), source);
            for (BeanDefinitionHolder processorDefinition : processorDefinitions) {
                compositeDef.addNestedComponent(new BeanComponentDefinition(processorDefinition));
            }
        }

        readerContext.fireComponentRegistered(compositeDef);
    }

 在这里我们关注的重点是registerComponents方法中的annotation-config属性的判断以及AnnotationConfigUtils的调用

3.AnnotationConfigUtilsregisterAnnotationConfigProcessors方法

 上面两个标签都用有同一个步骤调用AnnotationConfigUtilsregisterAnnotationConfigProcessors的方法。这个方法也是与AutowiredAnnotationBeanPostProcessor有关系的这个直接进去

    public static final String CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME =
            "org.springframework.context.annotation.internalConfigurationAnnotationProcessor";

public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
            BeanDefinitionRegistry registry, @Nullable Object source) {

        DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
        if (beanFactory != null) {
            if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
                beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
            }
            if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
                beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
            }
        }

        Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);
//如果registry中没有包含AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME这个beanName,则创建一个beanName为AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME的Bean并注册然后放到BeanDefinitionHolder的集合中
        if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
            RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
            def.setSource(source);
            beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
        }
      .......
}

 上面步骤的主要逻辑就是创建一个名称为AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME类型为AutowiredAnnotationBeanPostProcessor的Bean然后包装之后返回。这个AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME表示的是"org.springframework.context.annotation.internalConfigurationAnnotationProcessor"这个字符串。接下来就要解析这个字符串跟AutowiredAnnotationBeanPostProcessor的关系了。

4.上下文刷新refresh时候创建AutowiredAnnotationBeanPostProcessor

 无论是老的xml形式配置的spring还是springboot容器的刷新都会调用到对应的AbstractApplicationContext类的refresh方法。关于这个方法前面有简单的介绍Spring源码解析——refresh方法这里就对这个方法中的registerBeanPostProcessors步骤进行分析。

    protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
            //实例化并注册所有BeanPostProcessor bean,
        PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
    }

到这里其实大家应该有一点联系了。前面我们把beanName注册到了BeanDefinitionHolder这里就是实例化了。进入到上面的PostProcessorRegistrationDelegate类的registerBeanPostProcessors方法。这里省略部分无关的代码

public static void registerBeanPostProcessors(
            ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
              //获取beanFactory中所有的BeanPostProcessor类型的beanName
        String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

        ......
        List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
        ......
        for (String ppName : postProcessorNames) {
            if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
                priorityOrderedPostProcessors.add(pp);
                /**
                 * 找到MergedBeanDefinitionPostProcessor并注册进去这里注册的
                 * @see AutowiredAnnotationBeanPostProcessor
                 */
                if (pp instanceof MergedBeanDefinitionPostProcessor) {
                    internalPostProcessors.add(pp);
                }
            }
          ......
}

 可以看到这里会先获取到所有的类型是BeanPostProcessorBeanName而前面我们就注册了AutowiredAnnotationBeanPostProcessor这个类,所以在这里的时候AutowiredAnnotationBeanPostProcessor会被通过调用getBean的方式进行实力跟初始化。

2.springboot中AutowiredAnnotationBeanPostProcessor的初始化

 前面分析了传统的spring应用的初始化,接下来就是springboot中的了。这里快速的讲解一下,后续会写文章分析。springboot的启动类的SpringApplicationrun方法中有一步是createApplicationContext这个方法会根据应用上下文分析应用类型创建不同的Web应用或者非Web应用

    protected ConfigurableApplicationContext createApplicationContext() {
        Class<?> contextClass = this.applicationContextClass;
        if (contextClass == null) {
            try {
                switch(this.webApplicationType) {
                case SERVLET:
                    contextClass = Class.forName("org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext");
                    break;
                case REACTIVE:
                    contextClass = Class.forName("org.springframework.boot.web.reactive.context.AnnotationConfigReactiveWebServerApplicationContext");
                    break;
                default:
                    contextClass = Class.forName("org.springframework.context.annotation.AnnotationConfigApplicationContext");
                }
            } catch (ClassNotFoundException var3) {
                throw new IllegalStateException("Unable create a default ApplicationContext, please specify an ApplicationContextClass", var3);
            }
        }

        return (ConfigurableApplicationContext)BeanUtils.instantiateClass(contextClass);
    }

 其中默认的是SERVLET应用,因此会创建一个AnnotationConfigServletWebServerApplicationContext类型的上下文。接下来看这个类的构造方法

    public AnnotationConfigServletWebServerApplicationContext() {
        this.reader = new AnnotatedBeanDefinitionReader(this);
        this.scanner = new ClassPathBeanDefinitionScanner(this);
    }

 这里创建两个对象一个是对于注解注入的支持的AnnotatedBeanDefinitionReader跟配置文件注入支持的ClassPathBeanDefinitionScanner。这里要进入的是AnnotatedBeanDefinitionReader类。

    public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
        Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
        Assert.notNull(environment, "Environment must not be null");
        this.registry = registry;
        this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
        AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
    }

 到这里应该就知道了springboot应用中如何初始化AutowiredAnnotationBeanPostProcessor的了。这里调用了前面说的registerAnnotationConfigProcessors,然后在springboot最后进行容器刷新的时候进行实例跟初始化。

2.AutowiredAnnotationBeanPostProcessor解析autowire标签

 前面分析了AutowiredAnnotationBeanPostProcessor的实例化跟初始化,接下来就是分析对应的解析的过程了。

1.何时调用解析方法

 在AutowiredAnnotationBeanPostProcessor中解析方法的逻辑就在实现的postProcessPropertyValues方法中。现在主要看这个方法在什么时候被调用的,这里可以参考一下前面的Spring源码----Spring的Bean生命周期流程图及代码解释
文章就知道在Bean初始化之前的属性填充中调用的。这里截取部分代码

protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
        //容器刷新上下文的之前的准备工作中会设置
            boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
        boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

        PropertyDescriptor[] filteredPds = null;
        if (hasInstAwareBpps) {
            if (pvs == null) {
                pvs = mbd.getPropertyValues();
            }
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof InstantiationAwareBeanPostProcessor) {
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                        //调用位置
                    PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
                    if (pvsToUse == null) {
                        if (filteredPds == null) {
                            filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
                        }
                        pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                        if (pvsToUse == null) {
                            return;
                        }
                    }
                    pvs = pvsToUse;
                }
            }
        }
}

2.解析步骤

现在分析解析Autowired以及其他标签的步骤

    public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {  
    //寻找当前bean中需要自动注入的注入数据源
        InjectionMetadata metadata = findAutowiringMetadata(beanName, bean.getClass(), pvs);
        try {
      //进行注入
            metadata.inject(bean, beanName, pvs);
        }
        catch (BeanCreationException ex) {
            throw ex;
        }
        catch (Throwable ex) {
            throw new BeanCreationException(beanName, "Injection of autowired dependencies failed", ex);
        }
        return pvs;
    }

1.寻找需要注入的数据源

 现在分析如何查找对应的需要注入的数据源

    private InjectionMetadata findAutowiringMetadata(String beanName, Class<?> clazz, @Nullable PropertyValues pvs) {
        // 获取bean的beanName作为缓存的key如果不存在beanName就用类目
        String cacheKey = (StringUtils.hasLength(beanName) ? beanName : clazz.getName());
        // 从需要注入的缓存中查找是否存在已经解析过的需要注入的数据源,
        InjectionMetadata metadata = this.injectionMetadataCache.get(cacheKey);
        //如果数据源不存在或者数据源对应的目标class不是当前bean的beanclass则需要刷新
        if (InjectionMetadata.needsRefresh(metadata, clazz)) {
            synchronized (this.injectionMetadataCache) {
                metadata = this.injectionMetadataCache.get(cacheKey);
                if (InjectionMetadata.needsRefresh(metadata, clazz)) {
                    if (metadata != null) {
                        metadata.clear(pvs);
                    }
             //查找并创建需要注入的数据源,然后保存到缓存中取

                    metadata = buildAutowiringMetadata(clazz);
                    this.injectionMetadataCache.put(cacheKey, metadata);
                }
            }
        }
        return metadata;
    }

 这里需要先说一下injectionMetadataCache这个缓存最开始是在什么时候保存信息的,因为AutowiredAnnotationBeanPostProcessor也实现了MergedBeanDefinitionPostProcessorpostProcessMergedBeanDefinition方法,而这个方法的调用在Bean的实例化之后属性填充之前这个在前面Spring源码----Spring的Bean生命周期流程图及代码解释中也有提到。而在次方法中又会调用上面这段代码。所以injectionMetadataCache就是在这个时候先填充一次的。

2.寻找需要注入的数据源

    private InjectionMetadata buildAutowiringMetadata(final Class<?> clazz) {
        //检查对应的bean的class对象是否包含Autowired,Value或者Inject注解
        if (!AnnotationUtils.isCandidateClass(clazz, this.autowiredAnnotationTypes)) {
            return InjectionMetadata.EMPTY;
        }

        List<InjectionMetadata.InjectedElement> elements = new ArrayList<>();
        Class<?> targetClass = clazz;

        do {
            final List<InjectionMetadata.InjectedElement> currElements = new ArrayList<>();
            //查找贴有Autowired,Value或者Inject注解的字段,并保存到currElements中
            ReflectionUtils.doWithLocalFields(targetClass, field -> {
                MergedAnnotation<?> ann = findAutowiredAnnotation(field);
                if (ann != null) {
                    if (Modifier.isStatic(field.getModifiers())) {
                        if (logger.isInfoEnabled()) {
                            logger.info("Autowired annotation is not supported on static fields: " + field);
                        }
                        return;
                    }
                    //确定带注释的字段或方法是否需要其依赖项。
                    boolean required = determineRequiredStatus(ann);
                    currElements.add(new AutowiredFieldElement(field, required));
                }
            });
            //查找贴有Autowired,Value或者Inject注解的方法,并保存到currElements中
            ReflectionUtils.doWithLocalMethods(targetClass, method -> {
                Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(method);
                if (!BridgeMethodResolver.isVisibilityBridgeMethodPair(method, bridgedMethod)) {
                    return;
                }
                MergedAnnotation<?> ann = findAutowiredAnnotation(bridgedMethod);
                if (ann != null && method.equals(ClassUtils.getMostSpecificMethod(method, clazz))) {
                    if (Modifier.isStatic(method.getModifiers())) {
                        if (logger.isInfoEnabled()) {
                            logger.info("Autowired annotation is not supported on static methods: " + method);
                        }
                        return;
                    }
                    if (method.getParameterCount() == 0) {
                        if (logger.isInfoEnabled()) {
                            logger.info("Autowired annotation should only be used on methods with parameters: " +
                                    method);
                        }
                    }
                    boolean required = determineRequiredStatus(ann);
                    //获取方法中需要的参数
                    PropertyDescriptor pd = BeanUtils.findPropertyForMethod(bridgedMethod, clazz);
                    currElements.add(new AutowiredMethodElement(method, required, pd));
                }
            });
            //合并所有的currElements
            elements.addAll(0, currElements);
            targetClass = targetClass.getSuperclass();
        }
        while (targetClass != null && targetClass != Object.class);
        //将源数据集合保存到InjectionMetadata中
        return InjectionMetadata.forElements(elements, clazz);
    }

 这里就简单的说明一下,主要的步骤就是遍历bean的class对象,获取其中的field跟method然后检查是否有autowiredAnnotationTypes集合中表示需要注入的标签的,如果有的话就保存到InjectionMetadata的内部InjectedElement对象中,最后统一保存在InjectionMetadata中并返回。

3.注入属性到源数据

 注入的过程也很简单,就是便利前面的InjectionMetadata中的InjectedElement然后进行反射注入,这里就把代码贴一下

    public void inject(Object target, @Nullable String beanName, @Nullable PropertyValues pvs) throws Throwable {
        //获取当前InjectionMetadata中的checkedElements
        Collection<InjectedElement> checkedElements = this.checkedElements;
        //转换成可以迭代的elementsToIterate
        Collection<InjectedElement> elementsToIterate =
                (checkedElements != null ? checkedElements : this.injectedElements);
        if (!elementsToIterate.isEmpty()) {
            //迭代elementsToIterate进行注入
            for (InjectedElement element : elementsToIterate) {
                if (logger.isTraceEnabled()) {
                    logger.trace("Processing injected element of bean '" + beanName + "': " + element);
                }
                element.inject(target, beanName, pvs);
            }
        }
    }
        protected void inject(Object target, @Nullable String requestingBeanName, @Nullable PropertyValues pvs)
                throws Throwable {

            if (this.isField) {
                Field field = (Field) this.member;
                ReflectionUtils.makeAccessible(field);
                field.set(target, getResourceToInject(target, requestingBeanName));
            }
            else {
                if (checkPropertySkipping(pvs)) {
                    return;
                }
                try {
                    Method method = (Method) this.member;
                    ReflectionUtils.makeAccessible(method);
                    method.invoke(target, getResourceToInject(target, requestingBeanName));
                }
                catch (InvocationTargetException ex) {
                    throw ex.getTargetException();
                }
            }
        }

 到这里整个Autowired,Value,Inject标签都处理完了。我们也可以自定义注入标签,只需要获取到AutowiredAnnotationBeanPostProcessor对象然后调用setAutowiredAnnotationType方法来放置自己定义的标签就可以了。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值