// Prepare the bean factory for use in this context. /** * org.springframework.beans.factory.support.DefaultListableBeanFactory * */ 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) { 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(); } } }
/** * Prepare this context for refreshing, setting its startup date and * active flag as well as performing any initialization of property sources. */ protectedvoidprepareRefresh() { // Switch to active. this.startupDate = System.currentTimeMillis(); // closed设置为false,active设置为true. this.closed.set(false); this.active.set(true);
// 根据log级别来进行输出 if (logger.isInfoEnabled()) { logger.info("Refreshing " + this); }
// Initialize any placeholder property sources in the context environment. // 目前该方法没有调用;目前没有做任何事情. 目测是应该留给子类之类的进行扩展的. initPropertySources();
// Validate that all properties marked as required are resolvable: // see ConfigurablePropertyResolver#setRequiredProperties //先调用getEnvironment()获取this()方法中创建出来的Environment来,然后走validateRequiredProperties方法来进行一些检验, //org.springframework.core.env.AbstractPropertyResolver#validateRequiredProperties //最后是走到了这个方法,如果this.requiredProperties中是有值的话,那么这里就会抛出一个异常来 getEnvironment().validateRequiredProperties(); // Store pre-refresh ApplicationListeners... // 这里是对 earlyApplicationListeners 进行判断,如果有值的话,就先会clear掉,然后再addAll //如果是没有值的话,就会new一个集合,然后赋值给this.earlyApplicationListeners参数 if (this.earlyApplicationListeners == null) { this.earlyApplicationListeners = newLinkedHashSet<>(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 这个参数 this.earlyApplicationEvents = newLinkedHashSet<>(); }
/** * * Configure the factory's standard context characteristics, * such as the context's ClassLoader and post-processors. * @param beanFactory the BeanFactory to configure */ protectedvoidprepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { // Tell the internal bean factory to use the context's class loader etc. //给beanFactory设置classLoader(加载bean) beanFactory.setBeanClassLoader(getClassLoader()); //这里根据classLoader来获取解析器,然后set到BeanFactory中去.(解析bean定义的表达式) beanFactory.setBeanExpressionResolver(newStandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); //属性编辑注册器,set到BeanFactory中 beanFactory.addPropertyEditorRegistrar(newResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks. //添加ApplicationContextAwareProcessor到BeanFactory中.该类是有实现BeanPostProcessor的 //BeanPostProcessor是在bean初始化完后,调用BeanPostProcessor进行扩展. beanFactory.addBeanPostProcessor(newApplicationContextAwareProcessor(this)); //忽略掉EnvironmentAware/EmbeddedValueResolverAware....ApplicationContextAware //这六个接口的注入(依赖). 因为ApplicationContextAwareProcessor中有做了这些事 beanFactory.ignoreDependencyInterface(EnvironmentAware.class); beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class); beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class); beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class); beanFactory.ignoreDependencyInterface(MessageSourceAware.class); beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// BeanFactory interface not registered as resolvable type in a plain factory. // MessageSource registered (and found for autowiring) as a bean. // BeanFactory,ResourceLoader,ApplicationEventPublisher,ApplicationContext这四个接口 //对应的bean都set到beanFactory中去. 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. //添加ApplicationListenerDetector(BeanPostProcessor)到beanFactory中去. beanFactory.addBeanPostProcessor(newApplicationListenerDetector(this));
// Detect a LoadTimeWeaver and prepare for weaving, if found. if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(newLoadTimeWeaverAwareProcessor(beanFactory)); // Set a temporary ClassLoader for type matching. beanFactory.setTempClassLoader(newContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); }
// Register default environment beans. //如果beanFactory中没有ENVIRONMENT_BEAN_NAME这个bean的话,就注入一个进去 if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment()); } // SYSTEM_PROPERTIES_BEAN_NAME也是一样,注入到beanFactory中去 if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties()); } //SYSTEM_ENVIRONMENT_BEAN_NAME同上 if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment()); } }
/** * Modify the application context's internal bean factory after its standard * initialization. All bean definitions will have been loaded, but no beans * will have been instantiated yet. This allows for registering special * BeanPostProcessors etc in certain ApplicationContext implementations. * @param beanFactory the bean factory used by the application context */ protectedvoidpostProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { }
/** * Instantiate and invoke all registered BeanFactoryPostProcessor beans, * respecting explicit order if given. * <p>Must be called before singleton instantiation. BeanFactoryPostProcessor: 用来修改Spring容器中已经存在的bean定义. BeanDefinitionRegistryPostProcessor: 是BeanFactoryPostProcessor的子类,作用和父类是一样的,不同的是,该使用的是BeanDefinitionRegistry对bean进行处理 */ protectedvoidinvokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) { //org.springframework.context.support.AbstractApplicationContext#getBeanFactoryPostProcessors,由于这里只是启动了单个Spring,返回的集合是没有值的. List<BeanFactoryPostProcessor> postProcessorsList = getBeanFactoryPostProcessors(); //System.out.println("postProcessorsList value ---> " + postProcessorsList); // System.out.println("beanFactory value 111111 ---> " + beanFactory); //借助PostProcessorRegistrationDelegate来处理PostProcessors. //对传入postProcessorsList进行迭代,如果PostProcessor是BeanDefinitionRegistryPostProcessor的话,就会强转然后调用postProcessBeanDefinitionRegistry方法(传入参数是beanFacotry),添加到registryProcessors集合中.如果不是的话,就会添加到regularPostProcessors集合中. //根据BeanDefinitionRegistryPostProcessor,从beanFactory中获取postProcessorNames, //进行迭代,如果是有PriorityOrdered接口的子类的话,就会从beanFactory中根据bean名字,类.class来获取BeanDefinitionRegistryPostProcessor,并且添加到currentRegistryProcessors集合中,ppName(名字的值)也会添加到processedBeans该集合中 //对currentRegistryProcessors进行排序,全部添加到registryProcessors集合中,invokeBeanDefinitionRegistryPostProcessors()该方法是调用BeanDefinitionRegistryPostProcessors的,调用完了然后清空currentRegistryProcessors这个集合. //同样方法获取postProcessorNames,processedBeans集合中不包含并且是Ordered的子类,然后添加到currentRegistryProcessors集合中,ppName也会添加到processedBeans集合中,同样的排序方式,添加到registryProcessors中,再调用invokeBeanDefinitionRegistryPostProcessors()方法,currentRegistryProcessors清空该集合. // 也就是到这里,可以看出来,处理的顺序,先是处理PriorityOrdered,再处理Ordered. // 然后使用一个while循环,继续获取BeanDefinitionRegistryPostProcessor对应的postProcessorNames,这个地方是为了防止有些没有调用到的,并且是processedBeans集合中不包含的,然后就会放入到currentRegistryProcessors这个集合中,排序currentRegistryProcessors集合,全部添加到registryProcessors中,调用invokeBeanDefinitionRegistryPostProcessors,也就是调用具体的PostProcessors. //invokeBeanFactoryPostProcessors(registryProcessors, beanFactory); //invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); // 之前的二个集合,registryProcessors和regularPostProcessors,在这里还是会继续调用. //然后根据BeanFactoryPostProcessor.class获取postProcessorNames数组,与上面的也是同样的方法, //对postProcessorNames进行迭代,如果是processedBeans(上面装的名字)如果包含了,就会跳过. /** 如果ppName,也就是迭代的值,是有PriorityOrdered的子类的话,就会从走beanFactory.getBean(ppName, BeanFactoryPostProcessor.class)获取出BeanFactoryPostProcessor放入到priorityOrderedPostProcessors集合中. 如果是Ordered的子类,就将名字放入到orderedPostProcessorNames集合中,如果上面三种都不满足的话,就会放入到nonOrderedPostProcessorNames集合中. 然后先排序priorityOrderedPostProcessors,再走invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory); 接着迭代orderedPostProcessorNames集合,然后从beanFactory中获取BeanFactoryPostProcessor,再就做与priorityOrderedPostProcessors一样的操作. 最后在做nonOrderedPostProcessors这个集合的,操作是与orderedPostProcessorNames一摸一样的. 最后在调用一个beanFactory的clearMetadataCache方法. 可以看到这个方法是先对BeanDefinitionRegistryPostProcessor.class进行处理,然后根据顺序PriorityOrdered-->Ordered--->没有, 这样的顺序执行的. 然后再处理BeanFactoryPostProcessor.class,处理方式是和BeanDefinitionRegistryPostProcessor.class也是一样的,根据顺序来进行处理. */ PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, postProcessorsList);
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor) // 获取beanFactory的tempClassLoader加载,并且beanFactory是包含了loadTimeWeaver这个bean的, //就会走if方法,可以看到是添加LoadTimeWeaverAwareProcessor到beanFactory的postProcessor中, //然后添加一个ClassLoader到beanFactory中 if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(newLoadTimeWeaverAwareProcessor(beanFactory)); beanFactory.setTempClassLoader(newContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } }
/** * Instantiate and register all BeanPostProcessor beans, * respecting explicit order if given. * <p>Must be called before any instantiation of application beans. */ protectedvoidregisterBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) { PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this); }
// 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中获取出个数 + postProcessorNames数组长度再加上一个1. intbeanProcessorTargetCount= beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length; //添加一个BeanPostProcessorChecker到beanFactory中.从名字上来,这个PostProcessor应该是进行检查的操作. beanFactory.addBeanPostProcessor(newBeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// Separate between BeanPostProcessors that implement PriorityOrdered, // Ordered, and the rest. List<BeanPostProcessor> priorityOrderedPostProcessors = newArrayList<>(); List<BeanPostProcessor> internalPostProcessors = newArrayList<>(); List<String> orderedPostProcessorNames = newArrayList<>(); List<String> nonOrderedPostProcessorNames = newArrayList<>();
// 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到beanFactory中去,并且ApplicationListenerDetector是有实现MergedBeanDefinitionPostProcessor接口的. beanFactory.addBeanPostProcessor(newApplicationListenerDetector(applicationContext)); }
/** * Template method which can be overridden to add context-specific refresh work. * Called on initialization of special beans, before instantiation of singletons. * <p>This implementation is empty. * @throws BeansException in case of errors * @see #refresh() */ protectedvoidonRefresh()throws BeansException { // For subclasses: do nothing by default. }
/** * Add beans that implement ApplicationListener as listeners. * Doesn't affect other listeners, which can be added without being beans. */ protectedvoidregisterListeners() { // Register statically specified listeners first. //getApplicationListeners()获取AbstractApplicationContext中的applicationListeners //getApplicationEventMulticaster()方法获取的applicationEventMulticaster,是在 //initApplicationEventMulticaster方法中有初始化的. //org.springframework.context.event.AbstractApplicationEventMulticaster#addApplicationListener,最后是走到了这里, //this.defaultRetriever.applicationListeners.add(listener);最后listener是添加到 //其内部内ListenerRetriever的applicationListeners参数中去了. for (ApplicationListener<?> listener : getApplicationListeners()) { getApplicationEventMulticaster().addApplicationListener(listener); }
// Do not initialize FactoryBeans here: We need to leave all regular beans // uninitialized to let post-processors apply to them! //根据ApplicationListener获取相应的beanNames数组,这里可以看到和之前获取PostProcessor是一样的 String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); //然后迭代, getApplicationListenerBean是走到了 //org.springframework.context.event.AbstractApplicationEventMulticaster#addApplicationListenerBean,也就是添加到了其内部类ListenerRetriever的applicationListenerBeans属性里面 for (String listenerBeanName : listenerBeanNames) { getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); }
// Publish early application events now that we finally have a multicaster... //使用this.earlyApplicationEvents的集合的值,赋值给变量earlyEventsToProcess, //然后给this.earlyApplicationEvents重置为null Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents; this.earlyApplicationEvents = null; //集合不是null并且是有值的话, if (earlyEventsToProcess != null) { for (ApplicationEvent earlyEvent : earlyEventsToProcess) { //org.springframework.context.event.SimpleApplicationEventMulticaster#invokeListener,这里是走到了这里,可以看到是对这个事件进行发布. // 然后会根据ApplicationListener去走onApplicationEvent方法 getApplicationEventMulticaster().multicastEvent(earlyEvent); } } }
/** * Finish the initialization of this context's bean factory, * initializing all remaining singleton beans. */ protectedvoidfinishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { // Initialize conversion service for this context. //如果beanFactory包含CONVERSION_SERVICE_BEAN_NAME,并且该CONVERSION_SERVICE_BEAN_NAME是 //ConversionService的子类的话,久满足条件,然后先从beanFactory中获取出bean,set给beanFactory中的conversionService属性 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. // beanFactory中没有EmbeddedValueResolver,也就是该方法返回的是false,然后就从environment中获取出来一个给add到beanFactory中去. if (!beanFactory.hasEmbeddedValueResolver()) { beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal)); }
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early. //根据LoadTimeWeaverAware获取出对用的names数组 String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
//然后迭代上面获取出来的数组,挨个调用getBean方法 for (String weaverAwareName : weaverAwareNames) { getBean(weaverAwareName); }
// Stop using the temporary ClassLoader for type matching. // tempClassLoader,temp的ClassLoader设置为null beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes. //org.springframework.beans.factory.support.DefaultListableBeanFactory#freezeConfiguration,该方法时走的这里. 其中可以看到是给configurationFrozen设置为true,然后beanName的集合转化为数组,并且赋值给this.frozenBeanDefinitionNames这个数组 beanFactory.freezeConfiguration();
/** * Finish the refresh of this context, invoking the LifecycleProcessor's * onRefresh() method and publishing the * {@link org.springframework.context.event.ContextRefreshedEvent}. */ protectedvoidfinishRefresh() { // Clear context-level resource caches (such as ASM metadata from scanning). //清除资源缓存 clearResourceCaches();
// Initialize lifecycle processor for this context. // 这个方法就会调用实现了 Lifecycle 接口的子类,并且执行其start方法 initLifecycleProcessor();
// Propagate refresh to lifecycle processor first. getLifecycleProcessor().onRefresh();
// Publish the final event. //发送一个刷新上下文的Event出去 publishEvent(newContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active. //org.springframework.context.support.LiveBeansView#applicationContexts //将AbstractApplicationContext添加到liveBean的applicationContexts集合中 LiveBeansView.registerApplicationContext(this); }