ApplicationContext context = new ClassPathXmlApplicationContext("Beans.xml")代码调试收获
1.通过super(parent)调用了父类AbstractApplicationContext的构造方法,使AbstractApplicationContext中
ResourcePatternResolver resourcePatternResolver=new PathMatchingResourcePatternResolver;引发学习http://cainiaoboke.iteye.com/blog/2327685
2.setConfigLocations(configLocations)调用父类AbstractRefreshableConfigApplicationContext的setConfigLocations方法,使中的private String[] configLocations=[Beans.xml]
3.重点refresh开始调用AbstractApplicationContext的refresh()方法
public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // 容器启动的预先准备,记录容器启动的时间和标记 prepareRefresh(); // 创建BeanFactory,如果已有就销毁,没有就创建。此类实现了对BeanDefinition的装载 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // 配置BeanFactory标准上下文特性,如类装载器,PostProcesser等 prepareBeanFactory(beanFactory); try { // 在bean被装载后,提供一个修改BeanFactory的入口 postProcessBeanFactory(beanFactory); // 调用postProcessBeanFactory invokeBeanFactoryPostProcessors(beanFactory); // 注册用于拦截bean创建过程中的BeanPostProcessors 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(); // 注册监听器 registerListeners(); // 完成容器的初始化,里面的preInstantiateSingletons()完成对单例对象的创建 finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event. finishRefresh(); } catch (BeansException ex) { // Destroy already created singletons to avoid dangling resources. beanFactory.destroySingletons(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } } }
容器启动的预先准备,记录容器启动的时间和标记 初始化PropertySources校验需要的properties protected void prepareRefresh() { this.startupDate = System.currentTimeMillis(); synchronized (this.activeMonitor) { this.active = true; } if (logger.isInfoEnabled()) { logger.info("Refreshing " + this); } // Initialize any placeholder property sources in the context environment initPropertySources(); // Validate that all properties marked as required are resolvable // see ConfigurablePropertyResolver#setRequiredProperties getEnvironment().validateRequiredProperties(); }
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
1. 加载XML文件,封装成Resource对象
2. 调用Reader对象方法读取XML文件内容,并将相关属性放到BeanDefinition实例3. 将BeanDefinition对象放到BeanFactory对象
对于默认的单例Bean在refresh中的
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory); 中实例化
对于非单例或延迟加载的Bean在refresh中的实例化在getbean方法时实例化
BeanPostProcessor的构造方法的调用都在refresh()中的
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
要点:
refresh()中initApplicationEventMulticaster();注册监听
registerBeanPostProcessors(beanFactory);注册BeanPostProcessor
这是BeanPostProcessor实现类构造器!! BeanPostProcessor在这里创建实例
finishRefresh();发送事件给刚注册的监听
finishBeanFactoryInitialization(beanFactory);里面是创建对象 属性赋值等,如下:
Hello World构造函数被调用了
setMessage 被调用了
EnvironmentAware 被调用了
ApplicationContextAware 被调用了
bean处理器:bean创建之前..
InitializingBean afterPropertiesSet 被调用了
int-method 被调用了
bean处理器:bean创建之后..
ApplicationListener 被调用了 (创建容器)
ApplicationListener 被调用了 (销毁容器)
DisposableBean 被调用了
destroy-method 被调用了
具体实现在AbstractAutowireCapableBeanFactory里
populateBean(beanName, mbd, instanceWrapper);里面是属性赋值,依赖注入
exposedObject = initializeBean(beanName, exposedObject, mbd);里面是:
EnvironmentAware 被调用了
ApplicationContextAware 被调用了
bean处理器:bean创建之前..
InitializingBean afterPropertiesSet 被调用了
int-method 被调用了
bean处理器:bean创建之后..
在 exposedObject = initializeBean(beanName, exposedObject, mbd);中有段代码:
①if (mbd == null || !mbd.isSynthetic()) {
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
这个就是处理BeanPostProcessor的,Aware接口的实现了,是因为在refresh中
prepareBeanFactory(beanFactory);里面添加了一个beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
所以说常用的aware接口方式是:在BeanPostProcessor中默认都加了一个ApplicationContextAwareProcessor,而这个ApplicationContextAwareProcessor实现了BeanPostProcessor接口,所以在加载后置处理器时就处理aware相关的逻辑
②invokeInitMethods(beanName, wrappedBean, mbd);
这个加载实现了先后加载InitializingBean 和有init-method方法
③wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
这个方法加载BeanPostProcessor的 postProcessAfterInitialization方法
package com.jhuc.test; import org.springframework.beans.BeansException; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationEvent; import org.springframework.context.ApplicationListener; import org.springframework.context.EnvironmentAware; import org.springframework.core.env.Environment; public class HelloWorld implements ApplicationContextAware,EnvironmentAware,InitializingBean,ApplicationListener,DisposableBean{ private String message; public HelloWorld(){ System.out.println("Hello World构造函数被调用了"); } public void setMessage(String message){ System.out.println("setMessage 被调用了"); this.message = message; } public String getMessage(){ return this.message; } public void byebye(){ System.out.println("int-method 被调用了"); } @Override public void setEnvironment(Environment environment) { System.out.println("EnvironmentAware 被调用了"); } @Override public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { System.out.println("ApplicationContextAware 被调用了"); } @Override public void afterPropertiesSet() throws Exception { System.out.println("InitializingBean afterPropertiesSet 被调用了"); } @Override public void onApplicationEvent(ApplicationEvent event) { System.out.println("ApplicationListener 被调用了"); } @Override public void destroy() throws Exception { System.out.println("DisposableBean 被调用了"); } public void destroyMethod(){ System.out.println("destroy-method 被调用了"); } }
package com.jhuc.test; import org.springframework.beans.BeansException; import org.springframework.beans.factory.config.BeanPostProcessor; public class MyBeanPostProcessor implements BeanPostProcessor { public MyBeanPostProcessor() { super(); System.out.println("这是BeanPostProcessor实现类构造器!!"); } @Override public Object postProcessAfterInitialization(Object bean, String arg1) throws BeansException { System.out.println("bean处理器:bean创建之后.."); return bean; } @Override public Object postProcessBeforeInitialization(Object bean, String arg1) throws BeansException { System.out.println("bean处理器:bean创建之前.."); return bean; } }