天天看點

Spring Bean生命周期-階段彙總,面試必備(十二)

以後面試問到Bean的生命周期再也不怕了!

看了這麼久的Spring源碼,想必對Spring的生命周期已經有了一定的了解,這次将之前零散的生命周期處理的事情貫穿起來,看過之後,一定對bean的生命周期有更深入的了解

Spring Bean生命周期-階段彙總,面試必備(十二)
與文無關

簡介

  1. 執行個體化
  2. 設定bean的Aware
  3. BeanPostProcessor.postProcessBeforeInitialization(Object bean, String beanName)
  4. InitializingBean.afterPorpertiesSet
  5. BeanPostProcessor.postProcessAfterInitialization(Object bean, String beanName)
  6. SmartInitializingSingleton.afterSingletonsInstantiated
  7. SmartLifecycle.start
  8. bean已經在spring容器的管理下,可以做我們想做的事
  9. SmartLifecycle.stop(Runnable callback)
  10. DisposableBean.destroy()

細節部分

  1. 執行個體化對應代碼,使用合适的初始化方案來建立一個新的bean執行個體,factory-method,或者構造器注入,或者簡單的直接執行個體化

執行個體化政策類:

InstantiationStrategy

執行個體化具體方法:

AbstractAutowireCapableBeanFactory.createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args)

  1. 設定bean的Aware。InitializingBean.afterPorpertiesSet,BeanPostProcessor對bean的加工處理基本上在一塊出現。

設定Aware方法順序:

  • BeanNameAware
  • BeanClassLoaderAware
  • BeanFactoryAware

BeanPostProcessor.postProcessBeforeInitialization

Spring Bean生命周期-階段彙總,面試必備(十二)

image.png

ApplicationContextAwareProcessor也會設定Aware:

  • EnvironmentAware
  • EmbeddedValueResolverAware
  • ResourceLoaderAware
  • ApplicationEventPublisherAware
  • MessageSourceAware
  • ApplicationContextAware

調用afterpropertiesSet方法:位于AbstractAutowireCapableBeanFactory.invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)方法中

protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
        
      // 設定Aware  
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged(new PrivilegedAction<Object>() {
                @Override
                public Object run() {
                    invokeAwareMethods(beanName, bean);
                    return null;
                }
            }, getAccessControlContext());
        }
        else {
            invokeAwareMethods(beanName, bean);
        }
        
      //BeanPostProcessor的postProcessBeforeInitialization  
        Object wrappedBean = bean;
        if (mbd == null || !mbd.isSynthetic()) {
            wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
        }

        try {
           //調用init方法,其判斷是否是InitializingBean的執行個體,然後調用afterPropertiesSet
            invokeInitMethods(beanName, wrappedBean, mbd);
        }
        catch (Throwable ex) {
            throw new BeanCreationException(
                    (mbd != null ? mbd.getResourceDescription() : null),
                    beanName, "Invocation of init method failed", ex);
        }
    
      //BeanPostProcessor的postProcessAfterInitialization  
        if (mbd == null || !mbd.isSynthetic()) {
            wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
        }
        return wrappedBean;
    }
           
  1. SmartInitializingSingleton.afterSingletonsInstantiated的調用位置

DefaultListableBeanFactory.preInstantiateSingletons方法,其在所有的bean都執行個體化完成之後調用

@Override
    public void preInstantiateSingletons() throws BeansException {
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Pre-instantiating singletons in " + this);
        }

        // Iterate over a copy to allow for init methods which in turn register new bean definitions.
        // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
        List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);

        // Trigger initialization of all non-lazy singleton beans...
        // 觸發執行個體化所有的非懶加載的單例
        for (String beanName : beanNames) {
           ...
        }

        // Trigger post-initialization callback for all applicable beans...
        // 觸發應用bean的post-initialization回調,也就是afterSingletonsInstantiated方法
        for (String beanName : beanNames) {
            Object singletonInstance = getSingleton(beanName);
            if (singletonInstance instanceof SmartInitializingSingleton) {
                final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        @Override
                        public Object run() {
                            smartSingleton.afterSingletonsInstantiated();
                            return null;
                        }
                    }, getAccessControlContext());
                }
                else {
                    smartSingleton.afterSingletonsInstantiated();
                }
            }
        }
    }
           
  1. SmartLifecycle.start在ApplicationContext結束重新整理finishRefresh時,getLifecycleProcessor().onRefresh();

判斷bean是否為SmartLifecycle并且autoStartup。

位于:

DefaultLifecycleProcessor.onRefresh

  1. stop方法在Application.close的時候,調用getLifecycleProcessor().stop()方法仍然在DefaultLifecycleProcessor内部
  1. DisposableBean.destroy方法,doCreateBean方法中會判斷bean是否有銷毀相關操作,實作了DisposableBean方法或定義了銷毀方法。

AbstractAutowireCapableBeanFactory.doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)

代碼示範

public class HelloWorld implements SmartInitializingSingleton,SmartLifecycle,InitializingBean,
        DisposableBean,MyInterface,BeanNameAware,ApplicationContextAware
{

    private final Log logger = LogFactory.getLog(getClass());
    private boolean isRunning;
    

    public HelloWorld() {
        System.out.println("執行個體化");
    }

    public void sayHello(){
        System.out.println("hello World");
    }

    public void afterSingletonsInstantiated() {
        System.out.println("SmartInitializingSingleton afterSingletonsInstantiated");
    }

    public void start() {
        isRunning = true;
        System.out.println("LifeCycle start");
    }

    public void stop() {
        System.out.println("LifeCycle stop");
    }

    public boolean isRunning() {
        return isRunning;
    }

    public boolean isAutoStartup() {
        return true;
    }

    public void stop(Runnable callback) {
        System.out.println("LifeScycle stop");
        callback.run();
    }

    public int getPhase() {
        return 0;
    }

    public void afterPropertiesSet() throws Exception {
        System.out.println("afterproperties set");
    }

    public void destroy() throws Exception {
        System.out.println("destroy");
    }

    public void my(String str) {
        System.out.println(str);
    }

    public void setBeanName(String name) {
        System.out.println("set bean Name aware");
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        System.out.println("set Application Aware");
    }
}


//MyInterface接口
public interface MyInterface {
    void my(String str);
}


//app.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="porcessor" class="me.aihe.MyBeanPostProcessor" />
    <bean id="hello" class="me.aihe.HelloWorld">

    </bean>
</beans>



//SpringApp
public class SpringApp {
    public static void main(String[] args) {
        ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("app.xml");
        HelloWorld hello = (HelloWorld) applicationContext.getBean("hello");
        hello.sayHello();
        applicationContext.close();
    }
}

           

運作結果:

Spring Bean生命周期-階段彙總,面試必備(十二)

最後

可對照源代碼自行驗證生命周期。

上一篇: Spring概述
下一篇: 一種錯覺