Spring中bean生命周期
2019-05-07 本文已影响0人
AlanSun2
- 构造方法(new)
- 依赖注入
- 以Aware为后缀的接口方法,例如:
BeanNameAware
,BeanClassLoaderAware
,BeanFactoryAware
- BeanPostProcessor#postProcessBeforeInitialization (这里也会有Aware注入,具体请看下面的源码)
- @PostConstruct
- InitializingBean#afterPropertiesSet
- bean中的
initMethod
属性指定的方法 - BeanPostProcessor#postProcessAfterInitialization
以下方法只有scope为singleton的bean才会被执行,对于protoType Spring是不管理的,也没必要管理。
- @PreDestroy
- DisposableBean#destroy
- bean中的
destroyMethod
属性指定的方法
如果生命周期回调方法方法名有相同的,该方法只执行一次。
5,6和7一般使用7,因为没有和spring耦合。9,10和11同上。
如果你通过@Bean
或者<bean />
注册bean,且bean定义没有指定destroyMethod
属性(destroyMethod
的默认值是inferred
),但是类中存在close
或shutdown
方法,则close
或shutdown
方法会被执行。因为Spring有一个自动推测的机制(即,inferred
)。如果close
或shutdown
方法同时存在,只会执行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<Object>) () -> {
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);
}
}
}