spring的ClassPathXmlApplicationContext根据xml源码解析
1、首先创建配置文件applicationContext.xml ,通过ClassPathXmlApplicationContext创建实例化工厂
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
2、深入ClassPathXmlApplicationContext,refresh函数中包含了几乎ApplicationContext中提供的全部功能,主要进行refresh()函数的解析
/** * Create a new ClassPathXmlApplicationContext with the given parent, * loading the definitions from the given XML files. * @param configLocations array of resource locations * @param refresh whether to automatically refresh the context, * loading all bean definitions and creating all singletons. * Alternatively, call refresh manually after further configuring the context. * @param parent the parent context * @throws BeansException if context creation failed * @see #refresh() */ public ClassPathXmlApplicationContext( String[] configLocations, boolean refresh, @Nullable ApplicationContext parent) throws BeansException { super(parent); setConfigLocations(configLocations); if (refresh) { refresh(); } }
3、refresh()大体结构
public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { //准备刷新的上下文环境,例如对系统属性或者环境变量进行准备及验证。 prepareRefresh(); //初始化BeanFactory,并进行XML文件读取, //这一步之后,ClassPathXmlApplicationContext实际上就已经包含了BeanFactory所提供的功能,也就是可以进行Bean的提取等基础操作了。 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); //对BeanFactory进行各种功能填充,@Qualifier与@Autowired这两个注解正是在这一步骤中增加的支持。 //设置@Autowired和 @Qualifier注解解析器QualifierAnnotationAutowireCandidateResolver prepareBeanFactory(beanFactory); try { //子类覆盖方法做额外的处理,提供了一个空的函数实现postProcessBeanFactory来方便程序员在业务上做进一步扩展。 postProcessBeanFactory(beanFactory); //激活各种BeanFactory处理器 invokeBeanFactoryPostProcessors(beanFactory); //注册拦截Bean创建的Bean处理器,这里只是注册,真正的调用是在getBean时候 registerBeanPostProcessors(beanFactory); //为上下文初始化Message源,即不同语言的消息体进行国际化处理 initMessageSource(); //初始化应用消息广播器,并放入“applicationEventMulticaster”bean中 initApplicationEventMulticaster(); //留给子类来初始化其它的Bean onRefresh(); //在所有注册的bean中查找Listener bean,注册到消息广播器中 registerListeners(); //初始化剩下的单实例(非惰性的) finishBeanFactoryInitialization(beanFactory); //完成刷新过程,通知生命周期处理器lifecycleProcessor刷新过程,同时发出ContextRefreshEvent通知别人 finishRefresh(); } finally { // Reset common introspection caches in Spring's core, since we // might not ever need metadata for singleton beans anymore... resetCommonCaches(); } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· AI与.NET技术实操系列(六):基于图像分类模型对图像进行分类