spring源码分析:spring生命周期二

Posted Small leaf

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了spring源码分析:spring生命周期二相关的知识,希望对你有一定的参考价值。

接着上一篇我们看看具体是哪里的代码执行了。

1.初始化BeanFactoryPostProcessor

invokeBeanFactoryPostProcessors(beanFactory);-->

PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());


List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
        for (String postProcessorName : nonOrderedPostProcessorNames) 
    //这里有一个getBean这里进行BeanFactoryPostProcessor的初始化操作    
    nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
        

//这里执行BeanFactoryPostProcessor.postProcessBeanFactory
    invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

执行BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry

    private static void invokeBeanDefinitionRegistryPostProcessors(
            Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry) 

        for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) 
            postProcessor.postProcessBeanDefinitionRegistry(registry);
        
    

2.执行BeanFactoryPostProcessor的postProcessBeanFactory

private static void invokeBeanFactoryPostProcessors(
            Collection<? extends BeanFactoryPostProcessor> postProcessors, ConfigurableListableBeanFactory beanFactory) 

        for (BeanFactoryPostProcessor postProcessor : postProcessors) 
            postProcessor.postProcessBeanFactory(beanFactory);
        
    

3.初始化BeanPostProcessor。

registerBeanPostProcessors(beanFactory);-->

protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) 
        PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
    


    public static void registerBeanPostProcessors(
            ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) 
....

    // Now, register all regular BeanPostProcessors.
        List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
        for (String ppName : nonOrderedPostProcessorNames) 
        //同样这里getBean对BeanPostProcessor进行实例化
            BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
            nonOrderedPostProcessors.add(pp);
            if (pp instanceof MergedBeanDefinitionPostProcessor) 
                internalPostProcessors.add(pp);
            
        
....

4.执行InstantiationAwareBeanPostProcessor.postProcessBeforeInstantiation
这里只以单例为例

AbstractBeanFactory.doGetBean(final String name, @Nullable final Class<T> requiredType,
            @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException 
...
    // Create bean instance.
                if (mbd.isSingleton()) 
                    sharedInstance = getSingleton(beanName, () -> 
                        try 
                            return createBean(beanName, mbd, args);
                        
                        catch (BeansException ex) 
                            // Explicitly remove instance from singleton cache: It might have been put there
                            // eagerly by the creation process, to allow for circular reference resolution.
                            // Also remove any beans that received a temporary reference to the bean.
                            destroySingleton(beanName);
                            throw ex;
                        
                    );
...


进入createBean
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
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.
            if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) 
                Class<?> targetType = determineTargetType(beanName, mbd);
                if (targetType != null) 
                    bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
                    if (bean != null) 
                        bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
                    
                
            
            mbd.beforeInstantiationResolved = (bean != null);
        
        return bean;
    
    protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) 
        for (BeanPostProcessor bp : getBeanPostProcessors()) 
            if (bp instanceof InstantiationAwareBeanPostProcessor) 
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
                if (result != null) 
                    return result;
                
            
        
        return null;
    
上面已经执行了postProcessBeforeInstantiation

5.执行bean的构造函数

进入Object beanInstance = doCreateBean(beanName, mbdToUse, args);


if (instanceWrapper == null) 
            //这里面进行初始化
            instanceWrapper = createBeanInstance(beanName, mbd, args);
        

6.执行
postProcessBeforeInstantiation.postProcessPropertyValues

进入populateBean(beanName, mbd, instanceWrapper);



if (hasInstAwareBpps || needsDepCheck) 
            PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
            if (hasInstAwareBpps) 
                for (BeanPostProcessor bp : getBeanPostProcessors()) 
                    if (bp instanceof InstantiationAwareBeanPostProcessor) 

//这里执行postProcessBeforeInstantiation.postProcessPropertyValues

                        pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                        if (pvs == null) 
                            return;
                        
                    
                
            
            if (needsDepCheck) 
                checkDependencies(beanName, mbd, filteredPds, pvs);
            
        


applyPropertyValues(beanName, mbd, bw, pvs);

7.为bean注入属性

applyPropertyValues(beanName, mbd, bw, pvs);

8.执行bean实现的有关Aware接口

进入  exposedObject = initializeBean(beanName, exposedObject, mbd);
//这里给Aware赋予aware接口的能力
invokeAwareMethods(beanName, bean);

9.执行BeanPostProcessor.postProcessBeforeInitialization

if (mbd == null || !mbd.isSynthetic()) 
            wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
        



    public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
            throws BeansException 

        Object result = existingBean;
        for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) 
            Object current = beanProcessor.postProcessBeforeInitialization(result, beanName);
            if (current == null) 
                return result;
            
            result = current;
        
        return result;
    

10.执行@PostConstrut初始化方法

执行CommonAnnotationBeanPostProcessor.postProcessBeforeInitialization具体为什么会调用该方法放在后面统一讲解

11.执行InitializingBean.

进入invokeInitMethods(beanName, wrappedBean, mbd);

protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
            throws Throwable 

        boolean isInitializingBean = (bean instanceof InitializingBean);
        if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) 
            if (logger.isDebugEnabled()) 
                logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
            
            if (System.getSecurityManager() != null) 
                try 
                    AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> 
                        ((InitializingBean) bean).afterPropertiesSet();
                        return null;
                    , getAccessControlContext());
                
                catch (PrivilegedActionException pae) 
                    throw pae.getException();
                
            
            else 
            //这里调用
                ((InitializingBean) bean).afterPropertiesSet();
            
        

        if (mbd != null) 
            String initMethodName = mbd.getInitMethodName();
            if (StringUtils.hasLength(initMethodName) &&
                    !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
                    !mbd.isExternallyManagedInitMethod(initMethodName)) 
                invokeCustomInitMethod(beanName, bean, mbd);
            
        
    

12.执行xml的init-method

if (mbd != null) 
            String initMethodName = mbd.getInitMethodName();
            if (StringUtils.hasLength(initMethodName) &&
                    !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
                    !mbd.isExternallyManagedInitMethod(initMethodName)) 
                invokeCustomInitMethod(beanName, bean, mbd);
            
        

13.执行BeanPostProcessor.postProcessAfterInitialization

if (mbd == null || !mbd.isSynthetic()) 
            wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
        
@Override
    public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
            throws BeansException 

        Object result = existingBean;
        for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) 
            Object current = beanProcessor.postProcessAfterInitialization(result, beanName);
            if (current == null) 
                return result;
            
            result = current;
        
        return result;
    

以上的代码以AbstractApplicationContext。。refresh和AbstractBeanFactory.doGetBean为入口一步步跟均能找到。

上篇讲解了spring生命周期,这篇讲解了spring哪里具体实现。下一篇就讲解应用了,注解如何实现,例如@Configutation,@Import,@PostConstrut等。

以上是关于spring源码分析:spring生命周期二的主要内容,如果未能解决你的问题,请参考以下文章

Spring Environment生命周期

从源码分析Spring的生命周期

Spring源码分析系列-Bean的生命周期(总结篇)

Spring源码分析系列-Bean的生命周期(总结篇)

Spring源码分析系列-Bean的生命周期(总结篇)

Spring源码分析系列-Bean的生命周期(总结篇)