Spring中bean生命周期

  1. 构造方法(new)
  2. 依赖注入
  3. 以Aware为后缀的接口方法的调用,例如:BeanNameAwareBeanClassLoaderAwareBeanFactoryAware
  4. BeanPostProcessor#postProcessBeforeInitialization (这里也会有Aware注入,具体请看下面的源码)
  5. @PostConstruct
  6. InitializingBean#afterPropertiesSet
  7. bean中的initMethod属性指定的方法
  8. BeanPostProcessor#postProcessAfterInitialization

以下方法只有scope为singleton的bean才会被执行,对于protoType Spring是不管理的,也没必要管理。

  1. @PreDestroy
  2. DisposableBean#destroy
  3. bean中的destroyMethod属性指定的方法

如果生命周期回调方法方法名有相同的,该方法只执行一次。

5,6和7一般使用7,因为没有和spring耦合。9,10和11同上。

如果你通过@Bean或者注册bean,且bean定义没有指定destroyMethod属性(destroyMethod的默认值是inferred),但是类中存在closeshutdown方法,则closeshutdown方法会被执行。因为Spring有一个自动推测的机制(即,inferred)。如果closeshutdown方法同时存在,只会执行close方法。如果不想使用自动推测机制,可以把destroyMethod属性置为空,如下所示:

@Bean(destroyMethod = "")

实操记录:

18:33:30.048 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@3d24753a
18:33:30.065 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalConfigurationAnnotationProcessor'
18:33:30.217 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerProcessor'
18:33:30.219 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myBeanFactoryPostProcessor'
18:33:30.219 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.event.internalEventListenerFactory'
调用MyBeanFactoryPostProcessor的postProcessBeanFactory
18:33:30.221 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalAutowiredAnnotationProcessor'
18:33:30.222 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'org.springframework.context.annotation.internalCommonAnnotationProcessor'
18:33:30.226 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myBeanPostProcessor'
18:33:30.244 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myConfig'
18:33:30.245 [main] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Creating shared instance of singleton bean 'myJavaBean'
MyJavaBean的构造函数被执行啦
调用setDesc方法
调用setRemark方法
BeanNameAware:我的名字是myJavaBean
BeanFactoryAware:我的工厂是org.springframework.beans.factory.support.DefaultListableBeanFactory@
BeanPostProcessor,对象myJavaBean调用初始化方法之前的数据: com.alan344.demo.MyJavaBean@6ef888f6
调用@PostConstruct
调用afterPropertiesSet方法
调用initMethod方法
BeanPostProcessor,对象myJavaBean调用初始化方法之后的数据:com.alan344.demo.MyJavaBean@6ef888f6
18:33:30.291 [main] DEBUG org.springframework.context.annotation.AnnotationConfigApplicationContext - Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@3d24753a, started on Tue May 07 18:33:30 CST 2019
@PreDestroy
调用DisposableBean#destroy方法
调用destroyMethod方法

从中还可以看出:

  • PostProcessBeanFactory只执行一次
  • BeanPostProcessor对于每个bean都会执行一次

还有,如果你的bean是基于Java configuration定义的,你可以直接在代码里调用方法来执行初始化操作!是不是很方便,想怎么来就怎么来,就不必拘泥于以上的实现,相当灵活。

源码

创建bean AbstractAutowireCapableBeanFactory -> createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
依赖注入 AbstractAutowireCapableBeanFactory -> createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) -> populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw)
初始化 AbstractAutowireCapableBeanFactory -> createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) -> initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged((PrivilegedAction) () -> {
                invokeAwareMethods(beanName, bean);
                return null;
            }, getAccessControlContext());
        }
        else {
            invokeAwareMethods(beanName, bean);//调用以Aware为后缀的接口的方法
        }

        Object wrappedBean = bean;
        if (mbd == null || !mbd.isSynthetic()) {
            wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);//bean后置处理器初始化
        }

        try {
            invokeInitMethods(beanName, wrappedBean, mbd);//调用初始化方法
        }
        catch (Throwable ex) {
            throw new BeanCreationException(
                    (mbd != null ? mbd.getResourceDescription() : null),
                    beanName, "Invocation of init method failed", ex);
        }
        if (mbd == null || !mbd.isSynthetic()) {
            wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);//bean后置处理器
        }

        return wrappedBean;
    }
 
 

invokeAwareMethods(final String beanName, final Object bean)

    private void invokeAwareMethods(final String beanName, final Object bean) {
        if (bean instanceof Aware) {
            if (bean instanceof BeanNameAware) {
                ((BeanNameAware) bean).setBeanName(beanName);
            }
            if (bean instanceof BeanClassLoaderAware) {
                ClassLoader bcl = getBeanClassLoader();
                if (bcl != null) {
                    ((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
                }
            }
            if (bean instanceof BeanFactoryAware) {
                ((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
            }
        }
    }

其余的Aware接口在Bean后置处理器中(ApplicationContextAwareProcessor)注入,如下:

private void invokeAwareInterfaces(Object bean) {
        if (bean instanceof Aware) {
            if (bean instanceof EnvironmentAware) {
                ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
            }
            if (bean instanceof EmbeddedValueResolverAware) {
                ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
            }
            if (bean instanceof ResourceLoaderAware) {
                ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
            }
            if (bean instanceof ApplicationEventPublisherAware) {
                ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
            }
            if (bean instanceof MessageSourceAware) {
                ((MessageSourceAware) bean).setMessageSource(this.applicationContext);
            }
            if (bean instanceof ApplicationContextAware) {
                ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
            }
        }
    }

你可能感兴趣的:(Spring中bean生命周期)