@Test publicvoidxmlApplicationContextTest(){ ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml"); User user = context.getBean("user", User.class); System.out.println(user); }
@Override publicvoidrefresh()throws BeansException, IllegalStateException { // 加锁 synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. // 准备刷新的上下文环境,见下文详解 prepareRefresh();
// Tell the subclass to refresh the internal bean factory. // 获取刷新后的beanFactory,一般都是创建一个DefaultListableBeanFactory,见下文详解 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context. // 使用当前上下文环境准备beanFactory,见下文详解 prepareBeanFactory(beanFactory);
try { // Allows post-processing of the bean factory in context subclasses. // beanFactory的后置处理,子类实现,这也算是beanFactory的扩展点 // AbstractRefreshableWebApplicationContext在这个方法内加入了request和session的作用域 postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context. // 调用所有BeanFactoryPostProcessors的实现类,见下文详解 invokeBeanFactoryPostProcessors(beanFactory);
// 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(); } } }
// Initialize any placeholder property sources in the context environment. // 初始化占位符属性资源,该方法是留给子类实现的,默认什么也不做 initPropertySources();
// Validate that all properties marked as required are resolvable: // see ConfigurablePropertyResolver#setRequiredProperties // 验证需要的属性文件是否都已经放入环境中 getEnvironment().validateRequiredProperties();
// Store pre-refresh ApplicationListeners... if (this.earlyApplicationListeners == null) { this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners); } else { // Reset local application listeners to pre-refresh state. // 在上下文刷新前重置监听器 this.applicationListeners.clear(); this.applicationListeners.addAll(this.earlyApplicationListeners); }
// Allow for the collection of early ApplicationEvents, // to be published once the multicaster is available... this.earlyApplicationEvents = new LinkedHashSet<>(); }
上面代码中的 destroyBeans() 最终会调用 DefaultListableBeanFactory#destroySingletons() ,该方法在 Spring IoC createBean 方法详解 一文中已经介绍过,这里不再赘述。
loadBeanDefinitions() 方法最终会创建 XmlBeanDefinitionReader#loadBeanDefinitions() 去加载 bean 的定义元信息,该方法在 Spring XML Bean 定义的加载和注册 一文中已经介绍过,这里不再赘述;其中对 context:componment-scan 标签的解析在 Spring IoC component-scan 节点详解 一文中介绍过,这里也不再赘述。
protectedvoidprepareBeanFactory(ConfigurableListableBeanFactory beanFactory){ // Tell the internal bean factory to use the context's class loader etc. // 设置beanFactory的classLoader为当前context的classLoader beanFactory.setBeanClassLoader(getClassLoader()); // 设置beanFactory的表达式语言处理器 beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); // 为beanFactory增加了一个的propertyEditor,这个主要是对bean的属性等设置管理的一个工具 beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks. // 添加bean扩展,主要是对ApplicationContext新增加的Aware接口进行调用 beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
// BeanFactory interface not registered as resolvable type in a plain factory. // MessageSource registered (and found for autowiring) as a bean. // 注册解决依赖,也就是说我们可以通过依赖注入来注入以下四种类型的bean beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory); beanFactory.registerResolvableDependency(ResourceLoader.class, this); beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this); beanFactory.registerResolvableDependency(ApplicationContext.class, this);
// Register early post-processor for detecting inner beans as ApplicationListeners. // 将是ApplicationListener类型的bean在BeanPostProcessor的初始化后回调方法中加入到context的监听器列表中 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found. // 增加对AspectJ支持 if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); // Set a temporary ClassLoader for type matching. beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); }
// Register default environment beans. // 如果beanFactory不存在名为environment的bean,添加默认的,该bean就和我们正常声明的单例bean一样 if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment()); } // 如果beanFactory不存在名为systemProperties的bean,添加默认的,该bean就和我们正常声明的单例bean一样 if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties()); } // 如果systemEnvironment不存在名为systemEnvironment的bean,添加默认的,该bean就和我们正常声明的单例bean一样 if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment()); } }
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor) if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } }
// Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let the bean factory post-processors apply to them! // Separate between BeanDefinitionRegistryPostProcessors that implement // PriorityOrdered, Ordered, and the rest. List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered. // 和上面的差不多只是这次是实现了Ordered接口的,并且没有处理过的 postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); } } sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear();
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear. // 和上面的差不多只是这次是所有的实现了BeanDefinitionRegistryPostProcessors的bean,并且没有处理过的 boolean reiterate = true; while (reiterate) { reiterate = false; postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); for (String ppName : postProcessorNames) { if (!processedBeans.contains(ppName)) { currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class)); processedBeans.add(ppName); reiterate = true; } } sortPostProcessors(currentRegistryProcessors, beanFactory); registryProcessors.addAll(currentRegistryProcessors); invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry); currentRegistryProcessors.clear(); }
// Now, invoke the postProcessBeanFactory callback of all processors handled so far. // 调用BeanFactoryPostProcessor的postProcessBeanFactory() invokeBeanFactoryPostProcessors(registryProcessors, beanFactory); invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); }
else { // Invoke factory processors registered with the context instance. invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory); }
// Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let the bean factory post-processors apply to them! // 获取所有BeanFactoryPostProcessor类型的beanName String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered, // Ordered, and the rest. List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>(); List<String> orderedPostProcessorNames = new ArrayList<>(); List<String> nonOrderedPostProcessorNames = new ArrayList<>(); // 遍历postProcessorNames for (String ppName : postProcessorNames) { // 如果已经处理过,直接跳过;因为BeanDefinitionRegistryPostProcessor继承于BeanFactoryPostProcessor // 所以postProcessorNames也包含BeanDefinitionRegistryPostProcessor类型的bean,这里会对BeanDefinitionRegistryPostProcessor类型的bean直接跳过 if (processedBeans.contains(ppName)) { // skip - already processed in first phase above } // 如果实现了PriorityOrdered接口,初始化该bean并添加进priorityOrderedPostProcessors elseif (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)); } // 如果实现了Ordered接口,将beanName添加进orderedPostProcessorNames elseif (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } // 正常的将beanName添加进nonOrderedPostProcessorNames else { nonOrderedPostProcessorNames.add(ppName); } }
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered. // 排序,然后调用BeanFactoryPostProcessors的postProcessBeanFactory() sortPostProcessors(priorityOrderedPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered. // 和上面的一样这里是实现了Ordered接口的 List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size()); for (String postProcessorName : orderedPostProcessorNames) { orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } sortPostProcessors(orderedPostProcessors, beanFactory); invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors. // 和上面的一样这里是正常的BeanFactoryPostProcessors List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size()); for (String postProcessorName : nonOrderedPostProcessorNames) { nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class)); } invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
// Clear cached merged bean definitions since the post-processors might have // modified the original metadata, e.g. replacing placeholders in values... beanFactory.clearMetadataCache(); }
// Register BeanPostProcessorChecker that logs an info message when // a bean is created during BeanPostProcessor instantiation, i.e. when // a bean is not eligible for getting processed by all BeanPostProcessors. // 已经注册进beanFactory的数量 + 手动注册的BeanPostProcessorChecker + 实现了BeanPostProcessor还未注册的bean的数量 int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length; beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// Separate between BeanPostProcessors that implement PriorityOrdered, // Ordered, and the rest. // 存储实现了PriorityOrdered接口的BeanPostProcessors List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>(); // 存储实现了MergedBeanDefinitionPostProcessor接口的BeanPostProcessors List<BeanPostProcessor> internalPostProcessors = new ArrayList<>(); // 存储实现了Ordered接口的BeanPostProcessors List<String> orderedPostProcessorNames = new ArrayList<>(); // 存储正常的BeanPostProcessors List<String> nonOrderedPostProcessorNames = new ArrayList<>();
// Re-register post-processor for detecting inner beans as ApplicationListeners, // moving it to the end of the processor chain (for picking up proxies etc). // 这里再次添加了ApplicationListenerDetector(之前在prepareBeanFactory()已经添加过)是为了获取代理 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext)); }
protectedvoidfinishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory){ // Initialize conversion service for this context. if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) && beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) { beanFactory.setConversionService( beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)); }
// Register a default embedded value resolver if no bean post-processor // (such as a PropertyPlaceholderConfigurer bean) registered any before: // at this point, primarily for resolution in annotation attribute values. if (!beanFactory.hasEmbeddedValueResolver()) { beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal)); }
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early. String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false); for (String weaverAwareName : weaverAwareNames) { getBean(weaverAwareName); }
// Stop using the temporary ClassLoader for type matching. beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes. // 冻结所有的bean定义,也就是bean定义将不被修改或任何进一步的处理 beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons. // 初始化非延迟的单例bean,见下文详解 beanFactory.preInstantiateSingletons(); }
publicvoidpreInstantiateSingletons()throws BeansException { if (logger.isTraceEnabled()) { logger.trace("Pre-instantiating singletons in " + this); }
// Iterate over a copy to allow for init methods which in turn register new bean definitions. // While this may not be part of the regular factory bootstrap, it does otherwise work fine. List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);