Spring流程-bean生命周期-一图解析
这里是一个关于bean加载过程的故事。
故事前提
创建一个项目,引及spring相关的依赖
配置文件准备bean.xml
在reources下创建一个bean.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-3.0.xsd">
<!-- id自己命名,class就是需要注入属性的类-->
<bean id="category" class="demo.spring.Category">
<!-- name就是属性的名称,value就是注入到该属性的值-->
<property name="name" value="Hello Word"/>
</bean>
</beans>
代码准备
package demo.spring;
public class Category {
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
private String name;
}
启动代码
package demo.spring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringAprun {
public static void main(String[] args) {
//在这里开始打Debug
ApplicationContext context = new ClassPathXmlApplicationContext("bean.xml");
}
}
创建bean总体流程简述
主要是创建这个ClassPathXmlApplicationContext(“bean.xml”);时,它是继承了AbstractApplicationContext,所以启动时即会进入到AbstractApplicationContext里的reflush()开始流程。
进入这个reflush()方法便开始了Spring加载bean过程的十几个方法,如下所示,相关说明在图中再说明哦。
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
// Destroy already created singletons to avoid dangling resources.
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// Propagate exception to caller.
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
上图
CSDN不支持过大图片,一个图分成两部分,下图是接着AbstractApplicationContext开始的。
附件
发现不支持啊!!!!!