Spring 源码 之 配置文件中的Bean在Spring中的创建过程
2018-03-31 14:46
501 查看
小编的这篇博客的主要目的:是为梳理Spring底层源码是如果创建XML配置Bean的流程,本篇博客凸显了单一职责:仅是列出了创建配置Bean过程中涉及到的主要类和方法,至于类的功能和方法细节还请博友查看小编后续的文章或者去网上搜索相关的资料,如果有不对的地方,还请大神帮忙指出,以供参考学习:
1. web.context.ContextLoaderListener类 项目启动后,web.xml配置文件会监听类org.springframework.web.context.ContextLoaderListener,并调用void contextInitialized(ServletContextEventevent)方法,开始自动始初始化Spring上下文WebApplicationContext。public void contextInitialized(ServletContextEvent event)
{
initWebApplicationContext(event.getServletContext());
}2.springframwork.web.context. ContextLoader类(ContextLoaderListener的父类); 调用该类的WebApplicationContextinitWebApplicationContext(ServletContext servletContext)方法 --->接着调用该类 的 void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac,ServletContext sc)方法; public WebApplicationContext initWebApplicationContext(ServletContext servletContext)
...(略)
if ((this.context instanceof ConfigurableWebApplicationContext)) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext)this.context;
if (!cwac.isActive())
{
if (cwac.getParent() == null)
{
ApplicationContext parent = loadParentContext(servletContext);
cwac.setParent(parent);
}
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
...(略)
}
3. springframwork.context.support. AbstractApplicationContext类;调用该类的void refresh()方法 ---> 接着调用该类的registerBeanPostProcessors(beanFactory)方法;public void refresh() throws BeansException, IllegalStateException
...(略)
postProcessBeanFactory(beanFactory);
invokeBeanFactoryPostProcessors(beanFactory);
registerBeanPostProcessors(beanFactory);
initMessageSource();
4. springframwork.context.support. PostProcessorRegistrationDelegate类(其没有继承任何类);调用该类的registerBeanPostProcessors(ConfigurableListableBeanFactorybeanFactory, AbstractApplicationContext applicationContext)方法;public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext)
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
...(略)
List<String> nonOrderedPostProcessorNames = new ArrayList();
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = (BeanPostProcessor)beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if ((pp instanceof MergedBeanDefinitionPostProcessor)) {
internalPostProcessors.add(pp);
...(略)
}
}
}5. springframwork.beans.factory.support. AbstractBeanFactory类;在执行第4步的方法是,调用了ConfigurableListableBeanFactorybeanFactory的方法<T> T getBean(String name,Class<T> requiredType)方法(有必要在这里解释一下这个方法:此方法在ConfigurableListableBeanFactory接口中并没有定义,而是在顶层的BeanFactory接口定义的,ConfigurableListableBeanFactory接口自然可以继承此接口的定义,而在实现ConfigurableListableBeanFactory接口的抽象类AbstractBeanFactory中实现了此接口。此方法的返回值向上转型为BeanPostProcessor类(看第4部代码共色部分),此处待解释)public <T> T getBean(String name, Class<T> requiredType) throws BeansException
return doGetBean(name, requiredType, null, false);
}---> 接着调用该类的<T> T doGetBean(String name, Class<T> requiredType,final Object[] args, boolean typeCheckOnly)方法;protected <T> T doGetBean(String name, Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
{
...(略)
else
{
String scopeName = mbd.getScope();
Scope scope = (Scope)this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, new ObjectFactory()
{
public Object getObject() throws BeansException {
AbstractBeanFactory.this.beforePrototypeCreation(beanName);
try {
return AbstractBeanFactory.this.createBean(beanName, mbd, args);
}
finally {
AbstractBeanFactory.this.afterPrototypeCreation(beanName);
}
}
});
...(略)
return bean;
}6. springframwork.beans.factory.support. AbstractAutowireCapableBeanFactory类调用该类的createBean(String beanName,RootBeanDefinition mbd, Object[] args)方法 protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args)
{
...(略)
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}---> 接着调用该类的Object doCreateBean(final String beanName, final RootBeanDefinitionmbd, Object[] args)方法protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, Object[] args)throws BeanCreationException
{
...(略)
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
}
...(略)
return exposedObject;
}
---> 接着调用该类的Object initializeBean(final String beanName, final Object bean, RootBeanDefinitionmbd)方法protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd)
{
...(略)
Object wrappedBean = bean;
if ((mbd =
9dc3
= null) || (!mbd.isSynthetic())) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
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);
}
return wrappedBean;
}
}
---> 接着调用该类的Object applyBeanPostProcessorsBeforeInitialization(ObjectexistingBean, String beanName)方法(初始化Bean前)public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException
{
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessBeforeInitialization(result, beanName); 完全初始化Bean前的操作
if (result == null) {
return result;
}
}
return result;
}
---> 接着调用该类的invokeInitMethods(String beanName, final Object bean,RootBeanDefinition mbd)方法(初始化Bean)protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable
{
...(略)
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction()
{
public Object run() throws Exception {
((InitializingBean)bean).afterPropertiesSet();
return null;
}
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
} else {
((InitializingBean)bean).afterPropertiesSet();
}
}
if (mbd != null) {
String initMethodName = mbd.getInitMethodName();
if ((initMethodName != null) && ((!isInitializingBean) || (!"afterPropertiesSet".equals(initMethodName))) &&
(!mbd.isExternallyManagedInitMethod(initMethodName))) {
invokeCustomInitMethod(beanName, bean, mbd); 完全初始化Bean的操作
}
}
}
---> 接着调用该类的Object applyBeanPostProcessorsAfterInitialization(ObjectexistingBean, String beanName) (初始化Bean后)public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException
{
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessAfterInitialization(result, beanName); // 完全初始化Bean后的操作
if (result == null) {
return result;
}
}
return result;
}
返回Object wrappedBean类型的对象(实际上是已经包装好的Bean,即初始化完成的Bean)。
至此,Spring初始化XML配置文件中配置的Bean已经完成。
1. web.context.ContextLoaderListener类 项目启动后,web.xml配置文件会监听类org.springframework.web.context.ContextLoaderListener,并调用void contextInitialized(ServletContextEventevent)方法,开始自动始初始化Spring上下文WebApplicationContext。public void contextInitialized(ServletContextEvent event)
{
initWebApplicationContext(event.getServletContext());
}2.springframwork.web.context. ContextLoader类(ContextLoaderListener的父类); 调用该类的WebApplicationContextinitWebApplicationContext(ServletContext servletContext)方法 --->接着调用该类 的 void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac,ServletContext sc)方法; public WebApplicationContext initWebApplicationContext(ServletContext servletContext)
...(略)
if ((this.context instanceof ConfigurableWebApplicationContext)) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext)this.context;
if (!cwac.isActive())
{
if (cwac.getParent() == null)
{
ApplicationContext parent = loadParentContext(servletContext);
cwac.setParent(parent);
}
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
...(略)
}
3. springframwork.context.support. AbstractApplicationContext类;调用该类的void refresh()方法 ---> 接着调用该类的registerBeanPostProcessors(beanFactory)方法;public void refresh() throws BeansException, IllegalStateException
...(略)
postProcessBeanFactory(beanFactory);
invokeBeanFactoryPostProcessors(beanFactory);
registerBeanPostProcessors(beanFactory);
initMessageSource();
...(略)}
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) { PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this); }
4. springframwork.context.support. PostProcessorRegistrationDelegate类(其没有继承任何类);调用该类的registerBeanPostProcessors(ConfigurableListableBeanFactorybeanFactory, AbstractApplicationContext applicationContext)方法;public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext)
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
...(略)
List<String> nonOrderedPostProcessorNames = new ArrayList();
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
BeanPostProcessor pp = (BeanPostProcessor)beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if ((pp instanceof MergedBeanDefinitionPostProcessor)) {
internalPostProcessors.add(pp);
...(略)
}
}
}5. springframwork.beans.factory.support. AbstractBeanFactory类;在执行第4步的方法是,调用了ConfigurableListableBeanFactorybeanFactory的方法<T> T getBean(String name,Class<T> requiredType)方法(有必要在这里解释一下这个方法:此方法在ConfigurableListableBeanFactory接口中并没有定义,而是在顶层的BeanFactory接口定义的,ConfigurableListableBeanFactory接口自然可以继承此接口的定义,而在实现ConfigurableListableBeanFactory接口的抽象类AbstractBeanFactory中实现了此接口。此方法的返回值向上转型为BeanPostProcessor类(看第4部代码共色部分),此处待解释)public <T> T getBean(String name, Class<T> requiredType) throws BeansException
return doGetBean(name, requiredType, null, false);
}---> 接着调用该类的<T> T doGetBean(String name, Class<T> requiredType,final Object[] args, boolean typeCheckOnly)方法;protected <T> T doGetBean(String name, Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
{
...(略)
else
{
String scopeName = mbd.getScope();
Scope scope = (Scope)this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, new ObjectFactory()
{
public Object getObject() throws BeansException {
AbstractBeanFactory.this.beforePrototypeCreation(beanName);
try {
return AbstractBeanFactory.this.createBean(beanName, mbd, args);
}
finally {
AbstractBeanFactory.this.afterPrototypeCreation(beanName);
}
}
});
...(略)
return bean;
}6. springframwork.beans.factory.support. AbstractAutowireCapableBeanFactory类调用该类的createBean(String beanName,RootBeanDefinition mbd, Object[] args)方法 protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args)
{
...(略)
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}---> 接着调用该类的Object doCreateBean(final String beanName, final RootBeanDefinitionmbd, Object[] args)方法protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, Object[] args)throws BeanCreationException
{
...(略)
Object exposedObject = bean;
try {
populateBean(beanName, mbd, instanceWrapper);
if (exposedObject != null) {
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
}
...(略)
return exposedObject;
}
---> 接着调用该类的Object initializeBean(final String beanName, final Object bean, RootBeanDefinitionmbd)方法protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd)
{
...(略)
Object wrappedBean = bean;
if ((mbd =
9dc3
= null) || (!mbd.isSynthetic())) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
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);
}
return wrappedBean;
}
}
---> 接着调用该类的Object applyBeanPostProcessorsBeforeInitialization(ObjectexistingBean, String beanName)方法(初始化Bean前)public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException
{
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessBeforeInitialization(result, beanName); 完全初始化Bean前的操作
if (result == null) {
return result;
}
}
return result;
}
---> 接着调用该类的invokeInitMethods(String beanName, final Object bean,RootBeanDefinition mbd)方法(初始化Bean)protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd) throws Throwable
{
...(略)
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged(new PrivilegedExceptionAction()
{
public Object run() throws Exception {
((InitializingBean)bean).afterPropertiesSet();
return null;
}
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
} else {
((InitializingBean)bean).afterPropertiesSet();
}
}
if (mbd != null) {
String initMethodName = mbd.getInitMethodName();
if ((initMethodName != null) && ((!isInitializingBean) || (!"afterPropertiesSet".equals(initMethodName))) &&
(!mbd.isExternallyManagedInitMethod(initMethodName))) {
invokeCustomInitMethod(beanName, bean, mbd); 完全初始化Bean的操作
}
}
}
---> 接着调用该类的Object applyBeanPostProcessorsAfterInitialization(ObjectexistingBean, String beanName) (初始化Bean后)public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException
{
Object result = existingBean;
for (BeanPostProcessor beanProcessor : getBeanPostProcessors()) {
result = beanProcessor.postProcessAfterInitialization(result, beanName); // 完全初始化Bean后的操作
if (result == null) {
return result;
}
}
return result;
}
返回Object wrappedBean类型的对象(实际上是已经包装好的Bean,即初始化完成的Bean)。
至此,Spring初始化XML配置文件中配置的Bean已经完成。
相关文章推荐
- Spring源码分析之配置文件加载并注册Bean
- Spring源码分析:Bean加载流程概览及配置文件读取
- spring源码学习 - 配置文件bean的初始化
- spring-01 spring的bean管理(使用配置文件方式创建对象 附代码)
- spring源码(3)之解析配置文件的过程
- Spring 创建Bean的过程及其源码浅析
- 学习笔记:springmvc4.3源码学习:spring解析配置文件过程
- Spring源码分析:Bean加载流程概览及配置文件读取
- spring学习教程7-spring容器创建bean对象的方式以及如何处理多个spring配置文件
- 模拟Spring中applicationContext.xml配置文件初始化bean的过程
- 通过DefaultListableBeanFactory加载.xml配置文件学习Spring-IoC容器注册/加载bean的机制(源码走读)
- 分析spring源码第五(三)篇:Spring中Bean的解析、加载、创建 过程总结
- Spring IOC 容器源码分析 - 创建单例 bean 的过程
- JavaConfig配置文件为Spring创建bean
- spring源码解析-从xml配置文件中获取bean
- spring在配置文件中bean对象创建的三种方式
- Spring-mybatis整合配置错误,显示不能创建spring配置文件中的sqlSessionFactory的Bean
- Spring 源码分析:Bean 加载流程概览及配置文件读取
- 2、Spring的LocalSessionFactoryBean创建过程源码分析
- Dubbo和Spring结合配置文件内容解析为bean的过程