Spring IOC:bean的生命周期与@Autowire(1)

全系列文章:

《Spring IOC:bean的生命周期与@Autowire(1)》

《Spring IOC:bean的生命周期与@Autowire(2)》

《Spring IOC:bean的生命周期与@Autowire(3)》​​​​​​​

目录

一、BeanFactoryPostProcessor#postProcessBeanFactory

二、AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation

        1、生命周期相关接口

        2、实例化前流程     

三、AbstractAutowireCapableBeanFactory#createBeanInstance

      1、determineConstructorsFromBeanPostProcessors

        1.1、AutowiredAnnotationBeanPostProcessor的注册

        1.2、AutowiredAnnotationBeanPostProcessor#determineCandidateConstructors


写在开头:本文为学习后的总结,可能有不到位的地方,错误的地方,欢迎各位指正。

        Spring在整个生命周期中提供了非常多的扩展节点,这使得我们可以有非常多的方式来对bean的创建过程进行自定义的调整。下面我们结合bean的创建过程,对其生命周期进行一遍整理。

一、BeanFactoryPostProcessor#postProcessBeanFactory

        在应用上下文刷新过程中,即AbstractApplicationContext#refresh的过程中,在解析并加载完BeanDefination后,会调用invokeBeanFactoryPostProcessors方法,其内部将会实例化并调用所有已注册的BeanFactoryPostProcessor。

        BeanFactoryPostProcessor 接口是 Spring 初始化 BeanFactory 时对外暴露的扩展点,Spring IoC 容器允许 BeanFactoryPostProcessor 在容器实例化任何 bean 之前读取 bean 的定义,并可以修改它。

    // AbstractApplicationContext#refresh
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
            // ...
            
            // 加载BeanDefination
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
			// 遍历BeanFactoryPostProcessor的实现类并调用其postProcessBeanFactory方法
			invokeBeanFactoryPostProcessors(beanFactory);
			// 将实现了BeanPostProcessor的类注册到 BeanFactory 中
			registerBeanPostProcessors(beanFactory);
			// 完成bean的创建
			finishRefresh();
			
	        // ...
    }
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    // getBeanFactoryPostProcessors(): 拿到当前应用上下文beanFactoryPostProcessors变量中的值
    // invokeBeanFactoryPostProcessors: 实例化并调用所有已注册的BeanFactoryPostProcessor
    PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
 
 
    if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
        beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
        beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    }
}

这里经常拿来比较的是invokeBeanFactoryPostProcessors与registerBeanPostProcessors这两个方法,前者是对BeanFactory的扩展(即BeanFactoryPostProcessor 接口,因此该接口的实现类重写的方法在该过程中就会被调用),而后者是对Bean的扩展(即BeanPostProcessor,将会在bean创建过程前后被调用,这里只是注册 )。这两个步骤具体的过程可以看我之前的文章

《Spring IOC:invokeBeanFactoryPostProcessors调用链》《Spring IOC:registerBeanPostProcessors调用链》

public interface BeanFactoryPostProcessor {

	void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;

}

二、AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation

        1、生命周期相关接口

        在介绍具体流程前,需要先介绍2个接口BeanPostProcessor与InstantiationAwareBeanPostProcessor ,后者继承自前者。注意这两个接口定义的方法一个是作用于实例化,一个作用于初始化。

public interface BeanPostProcessor {
    // bean初始化前方法
	Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException;
    // bean初始化后方法
	Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException;
}
public interface InstantiationAwareBeanPostProcessor extends BeanPostProcessor {
    // bean实例化前方法
	Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) throws BeansException;
    // bean实例化后方法
	boolean postProcessAfterInstantiation(Object bean, String beanName) throws BeansException;
    // 属性注入相关
	PropertyValues postProcessPropertyValues(
			PropertyValues pvs, PropertyDescriptor[] pds, Object bean, String beanName) throws BeansException;
}

        2、实例化前流程     

        在createBean的过程中,会调用resolveBeforeInstantiation进行实例化前的处理。

    // AbstractAutowireCapableBeanFactory
	protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
        // ...

		try {
            // 
			Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
			if (bean != null) {
				return bean;
			}
		}
		catch (Throwable ex) {
			throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
					"BeanPostProcessor before instantiation of bean failed", ex);
		}

        // 创建bean
		Object beanInstance = doCreateBean(beanName, mbdToUse, args);

		return beanInstance;
	}

         在resolveBeforeInstantiation方法中,会在下面第3步时依次调用所有InstantiationAwareBeanPostProcessor接口的实现类的postProcessBeforeInstantiation方法。如果存在特殊情况,直接返回了代理对象,则直接为这个bean进行实例化后操作(这个操作我们后文介绍)。

protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
    Object bean = null;
    if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
        // Make sure bean class is actually resolved at this point.
        // 1.mbd不是合成的,并且BeanFactory中存在InstantiationAwareBeanPostProcessor
        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            // 2.解析beanName对应的Bean实例的类型
            Class<?> targetType = determineTargetType(beanName, mbd);
            if (targetType != null) {
                // 3.实例化前的后置处理器应用(处理InstantiationAwareBeanPostProcessor)
                bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
                if (bean != null) {
                    // 4.如果返回的bean不为空,会跳过Spring默认的实例化过程,
                    // 所以只能在这里调用BeanPostProcessor实现类的postProcessAfterInitialization方法
                    bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
                }
            }
        }
        // 5.如果bean不为空,则将beforeInstantiationResolved赋值为true,代表在实例化之前已经解析
        mbd.beforeInstantiationResolved = (bean != null);
    }
    return bean;
}
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
    // 1.遍历当前BeanFactory中的BeanPostProcessor
    for (BeanPostProcessor bp : getBeanPostProcessors()) {
        // 2.应用InstantiationAwareBeanPostProcessor后置处理器,允许postProcessBeforeInstantiation方法返回bean对象的代理
        if (bp instanceof InstantiationAwareBeanPostProcessor) {
            InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
            // 3.执行postProcessBeforeInstantiation方法,在Bean实例化前操作,
            // 该方法可以返回一个构造完成的Bean实例,从而不会继续执行创建Bean实例的“正规的流程”,达到“短路”的效果。
            Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
            if (result != null) {
                // 4.如果result不为空,也就是有后置处理器返回了bean实例对象,则会跳过Spring默认的实例化过程
                return result;
            }
        }
    }
    return null;
}

        前置操作之后,会进入到doCreateBean方法中,了解spring的朋友都知道,do开头的方法,代表一个流程真正开始执行。这里对将bean的完整创建过程进行了拆分,我们先看第一部分,bean的实例化。

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
        throws BeanCreationException {
 
    // Instantiate the bean.
    // 1.新建Bean包装类
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
        // 2.如果是FactoryBean,则需要先移除未完成的FactoryBean实例的缓存
        instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
        // 3.根据beanName、mbd、args,使用对应的策略创建Bean实例,并返回包装类BeanWrapper
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    // ...
}

三、AbstractAutowireCapableBeanFactory#createBeanInstance

protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args) {
    // Make sure bean class is actually resolved at this point.
    // 解析bean的类型信息
    Class<?> beanClass = resolveBeanClass(mbd, beanName);
 
    if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
        // beanClass不为空 && beanClass不是公开类(不是public修饰) && 该bean不允许访问非公共构造函数和方法,则抛异常
        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                "Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
    }
 
    // 1.如果存在工厂方法则使用工厂方法实例化bean对象
    if (mbd.getFactoryMethodName() != null) {
        return instantiateUsingFactoryMethod(beanName, mbd, args);
    }
 
    // Shortcut when re-creating the same bean...
    // resolved: 构造函数或工厂方法是否已经解析过
    boolean resolved = false;
    // autowireNecessary: 是否需要自动注入(即是否需要解析构造函数参数)
    boolean autowireNecessary = false;
    if (args == null) {
        // 2.加锁
        synchronized (mbd.constructorArgumentLock) {
            if (mbd.resolvedConstructorOrFactoryMethod != null) {
                // 2.1 如果resolvedConstructorOrFactoryMethod缓存不为空,则将resolved标记为已解析
                resolved = true;
                // 2.2 根据constructorArgumentsResolved判断是否需要自动注入
                autowireNecessary = mbd.constructorArgumentsResolved;
            }
        }
    }
 
    if (resolved) {
        // 3.如果已经解析过,则使用resolvedConstructorOrFactoryMethod缓存里解析好的构造函数方法
        if (autowireNecessary) {
            // 3.1 需要自动注入,则执行构造函数自动注入
            return autowireConstructor(beanName, mbd, null, null);
        } else {
            // 3.2 否则使用默认的构造函数进行bean的实例化
            return instantiateBean(beanName, mbd);
        }
    }
 
    // Need to determine the constructor...
    // 4.应用后置处理器SmartInstantiationAwareBeanPostProcessor,拿到bean的候选构造函数
    Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
    if (ctors != null ||
            mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_CONSTRUCTOR ||
            mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
        // 5.如果ctors不为空 || mbd的注入方式为AUTOWIRE_CONSTRUCTOR || mdb定义了构造函数的参数值 || args不为空,则执行构造函数自动注入
        return autowireConstructor(beanName, mbd, ctors, args);
    }
 
    // No special handling: simply use no-arg constructor.
    // 6.没有特殊处理,则使用默认的构造函数进行bean的实例化
    return instantiateBean(beanName, mbd);
}

1、determineConstructorsFromBeanPostProcessors

        该方法会遍历SmartInstantiationAwareBeanPostProcessor实现类,调用其determineCandidateConstructors方法查找出当前bean的候选构造函数。

protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(Class<?> beanClass, String beanName)
        throws BeansException {
 
    if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
        // 1.遍历所有的BeanPostProcessor
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
                SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
                // 2.调用SmartInstantiationAwareBeanPostProcessor的determineCandidateConstructors方法,
                // 该方法可以返回要用于beanClass的候选构造函数
                // 例如:使用@Autowire注解修饰构造函数,则该构造函数在这边会被AutowiredAnnotationBeanPostProcessor找到
                Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
                if (ctors != null) {
                    // 3.如果ctors不为空,则不再继续执行其他的SmartInstantiationAwareBeanPostProcessor
                    return ctors;
                }
            }
        }
    }
    return null;
}

        这里需要介绍一个非常重要的SmartInstantiationAwareBeanPostProcessor的实习类,即AutowiredAnnotationBeanPostProcessor 类,@Autowire便是基于此类实现的。下图展示了该类的继承关系,可以看出该类也是bean后置处理器的实现类。

        1.1、AutowiredAnnotationBeanPostProcessor的注册

        在之前的文章《Spring IOC:ComponentScanBeanDefinitionParser调用链》中,在registerAnnotationConfigProcessors方法中会注册spring自带的后置处理器,其中就包括了AutowiredAnnotationBeanPostProcessor。

public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
        BeanDefinitionRegistry registry, Object source) {
 
    DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
    if (beanFactory != null) {
        if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
            // 设置dependencyComparator属性
            beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
        }
    // 注册内部管理的用于处理@Autowired、@Value、@Inject以及@Lookup注解的后置处理器的bean
    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));
    }
     // ...
    return beanDefs;
}
 
private static BeanDefinitionHolder registerPostProcessor(
        BeanDefinitionRegistry registry, RootBeanDefinition definition, String beanName) {
 
    // 设置role
    definition.setRole(BeanDefinition.ROLE_INFRASTRUCTURE);
    // 注册BeanDefinition
    registry.registerBeanDefinition(beanName, definition);
    // 封装成BeanDefinitionHolder并返回
    return new BeanDefinitionHolder(definition, beanName);
}

        1.2、AutowiredAnnotationBeanPostProcessor#determineCandidateConstructors

        该方法用于确定要用于给定 bean 的候选构造函数。

@Override
public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, final String beanName)
        throws BeanCreationException {
 
    // Let's check for lookup methods here..
    // @Lookup注解检查
    if (!this.lookupMethodsChecked.contains(beanName)) {
        try {
            ReflectionUtils.doWithMethods(beanClass, new ReflectionUtils.MethodCallback() {
                @Override
                public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
                    Lookup lookup = method.getAnnotation(Lookup.class);
                    if (lookup != null) {
                        LookupOverride override = new LookupOverride(method, lookup.value());
                        try {
                            RootBeanDefinition mbd = (RootBeanDefinition) beanFactory.getMergedBeanDefinition(beanName);
                            mbd.getMethodOverrides().addOverride(override);
                        } catch (NoSuchBeanDefinitionException ex) {
                            throw new BeanCreationException(beanName,
                                    "Cannot apply @Lookup to beans without corresponding bean definition");
                        }
                    }
                }
            });
        } catch (IllegalStateException ex) {
            throw new BeanCreationException(beanName, "Lookup method resolution failed", ex);
        } catch (NoClassDefFoundError err) {
            throw new BeanCreationException(beanName, "Failed to introspect bean class [" + beanClass.getName() +
                    "] for lookup method metadata: could not find class that it depends on", err);
        }
        // 已经检查过的添加到lookupMethodsChecked
        this.lookupMethodsChecked.add(beanName);
    }
 
    // Quick check on the concurrent map first, with minimal locking.
    // 1.构造函数解析,首先检查是否存在于缓存中
    Constructor<?>[] candidateConstructors = this.candidateConstructorsCache.get(beanClass);
    if (candidateConstructors == null) {
        // Fully synchronized resolution now...
        // 2.加锁进行操作
        synchronized (this.candidateConstructorsCache) {
            // 3.再次检查缓存,双重检测
            candidateConstructors = this.candidateConstructorsCache.get(beanClass);
            if (candidateConstructors == null) {
                // 存放原始的构造函数(候选者)
                Constructor<?>[] rawCandidates;
                try {
                    // 4.获取beanClass声明的构造函数(如果没有声明,会返回一个默认的无参构造函数)
                    rawCandidates = beanClass.getDeclaredConstructors();
                } catch (Throwable ex) {
                    throw new BeanCreationException(beanName,
                            "Resolution of declared constructors on bean Class [" + beanClass.getName() +
                                    "] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
                }
                // 存放使用了@Autowire注解的构造函数
                List<Constructor<?>> candidates = new ArrayList<Constructor<?>>(rawCandidates.length);
                // 存放使用了@Autowire注解,并且require=true的构造函数
                Constructor<?> requiredConstructor = null;
                // 存放默认的构造函数
                Constructor<?> defaultConstructor = null;
                // 5.遍历原始的构造函数候选者
                for (Constructor<?> candidate : rawCandidates) {
                    // 6.获取候选者的注解属性
                    AnnotationAttributes ann = findAutowiredAnnotation(candidate);
                    if (ann == null) {
                        // 7.如果没有从候选者找到注解,则尝试解析beanClass的原始类(针对CGLIB代理)
                        Class<?> userClass = ClassUtils.getUserClass(beanClass);
                        if (userClass != beanClass) {
                            try {
                                Constructor<?> superCtor =
                                        userClass.getDeclaredConstructor(candidate.getParameterTypes());
                                ann = findAutowiredAnnotation(superCtor);
                            } catch (NoSuchMethodException ex) {
                                // Simply proceed, no equivalent superclass constructor found...
                            }
                        }
                    }
                    // 8.如果该候选者使用了@Autowire注解
                    if (ann != null) {
                        if (requiredConstructor != null) {
                            // 8.1 之前已经存在使用@Autowired(required = true)的构造函数,则不能存在其他使用@Autowire注解的构造函数,否则抛异常
                            throw new BeanCreationException(beanName,
                                    "Invalid autowire-marked constructor: " + candidate +
                                            ". Found constructor with 'required' Autowired annotation already: " +
                                            requiredConstructor);
                        }
                        // 8.2 获取注解的require属性值
                        boolean required = determineRequiredStatus(ann);
                        if (required) {
                            if (!candidates.isEmpty()) {
                                // 8.3 如果当前候选者是@Autowired(required = true),则之前不能存在其他使用@Autowire注解的构造函数,否则抛异常
                                throw new BeanCreationException(beanName,
                                        "Invalid autowire-marked constructors: " + candidates +
                                                ". Found constructor with 'required' Autowired annotation: " +
                                                candidate);
                            }
                            // 8.4 如果该候选者使用的注解的required属性为true,赋值给requiredConstructor
                            requiredConstructor = candidate;
                        }
                        // 8.5 将使用了@Autowire注解的候选者添加到candidates
                        candidates.add(candidate);
                    } else if (candidate.getParameterTypes().length == 0) {
                        // 8.6 如果没有使用注解,并且没有参数,则为默认的构造函数
                        defaultConstructor = candidate;
                    }
                }
                // 9.如果存在使用了@Autowire注解的构造函数
                if (!candidates.isEmpty()) {
                    // Add default constructor to list of optional constructors, as fallback.
                    // 9.1 但是没有使用了@Autowire注解并且required属性为true的构造函数
                    if (requiredConstructor == null) {
                        if (defaultConstructor != null) {
                            // 9.2 如果存在默认的构造函数,则将默认的构造函数添加到candidates
                            candidates.add(defaultConstructor);
                        } else if (candidates.size() == 1 && logger.isWarnEnabled()) {
                            logger.warn("Inconsistent constructor declaration on bean with name '" + beanName +
                                    "': single autowire-marked constructor flagged as optional - " +
                                    "this constructor is effectively required since there is no " +
                                    "default constructor to fall back to: " + candidates.get(0));
                        }
                    }
                    // 9.3 将所有的candidates当作候选者
                    candidateConstructors = candidates.toArray(new Constructor<?>[candidates.size()]);
                } else if (rawCandidates.length == 1 && rawCandidates[0].getParameterTypes().length > 0) {
                    // 10.如果candidates为空 && beanClass只有一个声明的构造函数(非默认构造函数),则将该声明的构造函数作为候选者
                    candidateConstructors = new Constructor<?>[]{rawCandidates[0]};
                } else {
                    // 11.否则返回一个空的Constructor对象
                    candidateConstructors = new Constructor<?>[0];
                }
                // 12.将beanClass的构造函数解析结果放到缓存
                this.candidateConstructorsCache.put(beanClass, candidateConstructors);
            }
        }
    }
    // 13.返回解析的构造函数
    return (candidateConstructors.length > 0 ? candidateConstructors : null);
}

         调用findAutowiredAnnotation方法获取构造方法上的的注解属性。

private AnnotationAttributes findAutowiredAnnotation(AccessibleObject ao) {
    // 1.判断ao是否有被注解修饰
    if (ao.getAnnotations().length > 0) {
        // 2.检查是否有autowiredAnnotationTypes中的注解:@Autowired、@Value(@Value无法修饰构造函数)
        for (Class<? extends Annotation> type : this.autowiredAnnotationTypes) {
            // 3.拿到注解的合并注解属性,@Autowire在这边拿到,required=true(默认属性)
            AnnotationAttributes attributes = AnnotatedElementUtils.getMergedAnnotationAttributes(ao, type);
            if (attributes != null) {
                return attributes;
            }
        }
    }
    return null;
}

        到这里,我们就找出了使用了@Autowire注解的构造方法,然后便是调用autowireConstructor为构造函数自动装配,这段内容在前文《Spring IoC源码学习:createBean调用链(1)》中第三节已经介绍,不多赘述。

       

        本文中的生命周期方法结合流程图展示如下:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值