@Override public void refresh() throws BeansException, IllegalStateException { // 使用对象锁 synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. // 通过设置AutomaticBoolean类型的close 和 active变量,表示环境开始刷新。 // 验证环境的信息,对于WebServer的上下文清空metadata cache。 prepareRefresh();
// 看上下文的类型,如果是可更新的会创建beanFactory,而GenericApplicationContext,就设置一个工厂的序列化ID // Tell the subclass to refresh the internal bean factory. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 准备spring BeanFactory,注入ClassLoader等 // 设置beanFactory.ignoreDependencyInterface,即针对ApplicationContext和BeanFactory这种使用PostProcessor的进行注入的bean,在Autowire中自动忽略注入。 // 注册两个后置处理器ApplicationContextAwareProcessor、ApplicationListenerDetector // Prepare the bean factory for use in this context. prepareBeanFactory(beanFactory);
try { // 主要注册了 Register ServletContextAwareProcessor(BeanPostProcessor) // Allows post-processing of the bean factory in context subclasses. postProcessBeanFactory(beanFactory);
// 调用三个BeanFactory级别的后置处理器,通过SharedMetadataReaderFactoryContextInitializer,注册对应的ConfigurationClassPostProcessor // 接着调用BeanDefinitionRegistryPostProcessor 级别的方法, 上述注册的ConfigurationClassPostProcessor被调用加载@Configuration // @SpringBootApplication 注解的类,在这边开始被加载进来的。并调用@EnableAutoConfiguration 的导入类@Import(AutoConfigurationImportSelector.class) // AutoConfigurationImportSelector会先加载进所有配置,先过滤exclude的autoConfiguration,在加载配置过滤器ConfigurationFilter,过滤配置(主要过滤@ConditionOnClass之类的依赖,并标明该AutoConfiguration是否需要加载) // 过滤完配置,调用AutoConfigurationImportEvent的事件监听,记录配置过滤结果,并且AutoConfigurationImportSelector 排序记录需要加载的autoConfiguration entry // 排序完的configurationList,通过栈的调用方式,依次加载@Configuration中@imports的类。最终ConfigurationClassParser会记载需要按顺序加载的Configuration List // 加载排序完成后的Configration的BeanDefinition,RefreshScope修改BeanDefinition(热加载,配置修改相关事项) // 最后调用BeanFactory级别的后置处理器。这边加入了propertySourcesPlaceholderConfigurer 用于替换占位符的。BeanFactory调用时区分后置处理器的顺序调用。 // Invoke factory processors registered as beans in the context. invokeBeanFactoryPostProcessors(beanFactory);
// Initialize message source for this context. initMessageSource();
// Initialize event multicaster for this context. initApplicationEventMulticaster();
// 对于Web的ApplicationContext,在这边新建初始化TomcatServer // 此时与Spring web 相关的东西被注册到beanfactory中 // Initialize other special beans in specific context subclasses. onRefresh();
// 此处把当前上下文的Listener注册到BeanFactory中 // Check for listener beans and register them. registerListeners();
// 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(); } } }
spring boot相关知识
Spring Cloud 构建于 Spring Boot 之上,在 Spring Boot 中有两种上下文,一种是 bootstrap,另外一种是 application,