以后面试问到豆的生命周期再也不怕了!
看了这么久的春天源码,想必对春天的生命周期已经有了一定的了解,这次将之前零散的生命周期处理的事情贯穿起来,看过之后,一定对豆的生命周期有更深入的理解
与文无关
简介
实例化设置豆的初始化前(对象比恩,字符串豆名)初始化后(对象比恩,字符串豆名)初始化后已经在春天容器的管理下,可以做我们想做的事SmartLifecycle.stop(可运行回调)DisposableBean.destroy()细节部分
实例化对应代码,使用合适的初始化方案来创建一个新的豆实例工厂方法,或者构造器注入,或者简单的直接实例化实例化策略类:
实例化策略
实例化具体方法:
abstractautowirecapablebeanstream。createbeainstance(字符串豆名,根BeanDefinition mbd,对象[]参数)
设置豆的意识到。初始化后处理器对豆的加工处理基本上在一块出现。设置知道的方法顺序:
bean name awarebeaanclasloadrewarerefactoryawarebeantprocessor。初始化前的后期处理
image.png
ApplicationContextAwareProcessor也会设置意识到:
环境意识调用后属性集方法:位于抽象方法(字符串豆名,最终对象比恩,根bean definition(mbd)方法中
受保护对象初始化豆(最终字符串豆名称,最终对象比恩,根豆定义mbd){ 0
//设置知道的
if (System.getSecurityManager()!=null){ 0
AccessController.doPrivileged(新的PrivilegedActionObject(){ 0
@覆盖
公共对象运行(){ 0
invokeawaremmethods(bean名称,bean);
返回空
}
},getAccessControlContext());
}
else {
invokeawaremmethods(bean名称,bean);
}
//bean后置处理器的初始化前的后处理
对象wrappedBean=bean
if (mbd==null ||!mbd。is dynamic()){ 0
wrappedBean=applyBeanpartprocessors beforegization(wrappedBean,bean名称);
}
尝试{
//调用初始化方法,其判断是否是InitializingBean的实例,然后调用后属性集
invokeInitMethods(beanName,wrappedBean,mbd);
}
捕获(Thr
owable 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的调用位置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(); } } } } SmartLifecycle.start在ApplicationContext结束刷新finishRefresh时,getLifecycleProcessor().onRefresh();判断bean是否为SmartLifecycle并且autoStartup。
位于:
DefaultLifecycleProcessor.onRefresh
stop方法在Application.close的时候,调用getLifecycleProcessor().stop()方法仍然在DefaultLifecycleProcessor内部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();
}
}
运行结果:
最后
可对照源代码自行验证生命周期