SpringIOC容器创建过程
在测试时,经常使用这种方式来创建spring容器
//创建基于注解的springIOC容器 ApplicationContext applicationContext = new AnnotationConfigApplicationContext(AopBeanConfig.class); //创建基于配置文件的springIOC容器 ApplicationContext applicationContext = new ClassPathXmlApplicationContext("/spring-beans.xml");
无论哪种方式,最终都会调用AbstractApplicationContext的一个重要方法——refresh(),首先来看这个方法的spring源码
SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。@Override public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // 1. Prepare this context for refreshing. prepareRefresh(); // 2. Tell the subclass to refresh the internal bean factory. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // 3. Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory); try { // 4. Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory); // 5. Invoke factory processors registered as beans in the context. invokeBeanFactoryPostProcessors(beanFactory); // 6. Register bean processors that intercept bean creation. registerBeanPostProcessors(beanFactory); // 7. Initialize message source for this context. initMessageSource(); // 8. Initialize event multicaster for this context. initApplicationEventMulticaster(); // 9. Initialize other special beans in specific context subclasses. onRefresh(); // 10. Check for listener beans and register them. registerListeners(); // 11. Instantiate all remaining (non-lazy-init) singletons. finishBeanFactoryInitialization(beanFactory); // 12. 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(); } } }
重点步骤简析
1. prepareRefresh 准备刷新容器
(1) initPropertySources() 自定义属性设置,空方法,留给子类继承
(2) getEnvironment.validateRequiredProperties 首先获取环境配置,然后校验必需属性
(3) this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners); 初始化事件监听器
(4) this.earlyApplicationEvents = new LinkedHashSet<>(); 初始化事件
2. obtainFreshBeanFactory 获取组件工厂
(1) refreshBeanFactory 新建一个组件工厂,类型为DefaultListableBeanFactory,然后对这个组件工厂设置了一个序列化ID
(2) getBeanFactory 返回刚刚创建的组件工厂
3. prepareBeanFactory 对组件工厂做各种预处理设置
(1) 在组件工厂中设置类加载器、属性解析器等
(2) 在组件工厂中添加部分组件后置处理器,例如ApplicationContextAwareProcessor、ApplicationListenerDetector
(3) 在组件工厂中设置忽略自动注入的接口
(4) 设置自动装配规则
(5) 在组件工厂中注册一些组件,例如环境配置ConfigurableEnvironment
4. postProcessBeanFactory 组件工厂的后置处理工作
