最近在看spring源码,顺便做一下记录
web工程
我们在用到struts2 或者springmvc时会引导实例化spring容器,那么这个引导入口在哪里呢?就在我们的web.xml里,就是我们需要配置的listener
<listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
普通java工程
初始化spring对象容器的入口是我们创建ClassPathXmlApplicationContext或者FileSystemXmlApplicationContext的时候
ApplicationContext ctx = new ClassPathXmlApplicationContext("bean.xml");// 读取bean.xml中的内容
ApplicationContext fctx = new FileSystemXmlApplicationContext("d:/aa.xml");
其中ContextLoaderListener实例化过程中首先会绑定一些web应用相关特性的对象然后会调用
org.springframework.context.support.AbstractApplicationContext.refresh()方法创建我们需要的类,完成依赖注入等
ApplicationContext实例化过程首先会设置一些配置文件路径,最后也是调用
org.springframework.context.support.AbstractApplicationContext.refresh()实例化容器,初始化类和依赖注入,
所以源码查看重心就在这个refresh方法了(每个版本会有细微差别)
代码还是挺清晰的:
public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. 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) { // Destroy already created singletons to avoid dangling resources. destroyBeans(); // Reset 'active' flag. cancelRefresh(ex); // Propagate exception to caller. throw ex; } } }
里面的方法我会分开用文章来写,方便阅读