以后面試問(wèn)到Bean的生命周期再也不怕了妨退!
看了這么久的Spring源碼咬荷,想必對(duì)Spring的生命周期已經(jīng)有了一定的了解,這次將之前零散的生命周期處理的事情貫穿起來(lái)懦底,看過(guò)之后基茵,一定對(duì)bean的生命周期有更深入的理解
簡(jiǎn)介
- 實(shí)例化
- 設(shè)置bean的Aware
- BeanPostProcessor.postProcessBeforeInitialization(Object bean, String beanName)
- InitializingBean.afterPorpertiesSet
- BeanPostProcessor.postProcessAfterInitialization(Object bean, String beanName)
- SmartInitializingSingleton.afterSingletonsInstantiated
- SmartLifecycle.start
- bean已經(jīng)在spring容器的管理下,可以做我們想做的事
- SmartLifecycle.stop(Runnable callback)
- DisposableBean.destroy()
細(xì)節(jié)部分
- 實(shí)例化對(duì)應(yīng)代碼宴咧,使用合適的初始化方案來(lái)創(chuàng)建一個(gè)新的bean實(shí)例掺栅,factory-method,或者構(gòu)造器注入桃笙,或者簡(jiǎn)單的直接實(shí)例化
實(shí)例化策略類:
InstantiationStrategy
實(shí)例化具體方法:
AbstractAutowireCapableBeanFactory.createBeanInstance(String beanName, RootBeanDefinition mbd, Object[] args)
- 設(shè)置bean的Aware沙绝。InitializingBean.afterPorpertiesSet搏明,BeanPostProcessor對(duì)bean的加工處理基本上在一塊出現(xiàn)。
設(shè)置Aware方法順序:
- BeanNameAware
- BeanClassLoaderAware
- BeanFactoryAware
BeanPostProcessor.postProcessBeforeInitialization
ApplicationContextAwareProcessor也會(huì)設(shè)置Aware:
- EnvironmentAware
- EmbeddedValueResolverAware
- ResourceLoaderAware
- ApplicationEventPublisherAware
- MessageSourceAware
- ApplicationContextAware
調(diào)用afterpropertiesSet方法:位于AbstractAutowireCapableBeanFactory.invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)方法中
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
// 設(shè)置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 {
//調(diào)用init方法闪檬,其判斷是否是InitializingBean的實(shí)例星著,然后調(diào)用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;
}
- SmartInitializingSingleton.afterSingletonsInstantiated的調(diào)用位置
DefaultListableBeanFactory.preInstantiateSingletons方法,其在所有的bean都實(shí)例化完成之后調(diào)用
@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...
// 觸發(fā)實(shí)例化所有的非懶加載的單例
for (String beanName : beanNames) {
...
}
// Trigger post-initialization callback for all applicable beans...
// 觸發(fā)應(yīng)用bean的post-initialization回調(diào)粗悯,也就是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();
}
}
}
}
- SmartLifecycle.start在ApplicationContext結(jié)束刷新finishRefresh時(shí)虚循,getLifecycleProcessor().onRefresh();
判斷bean是否為SmartLifecycle并且autoStartup样傍。
位于:
DefaultLifecycleProcessor.onRefresh
- stop方法在Application.close的時(shí)候横缔,調(diào)用getLifecycleProcessor().stop()方法仍然在DefaultLifecycleProcessor內(nèi)部
- DisposableBean.destroy方法,doCreateBean方法中會(huì)判斷bean是否有銷(xiāo)毀相關(guān)操作衫哥,實(shí)現(xiàn)了DisposableBean方法或定義了銷(xiāo)毀方法茎刚。
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("實(shí)例化");
}
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();
}
}
運(yùn)行結(jié)果:
最后
可對(duì)照源代碼自行驗(yàn)證生命周期。