執行完前面的步驟后, 回到 org.springframework.context.support.AbstractApplicationContext#refresh 方法.
@Override public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // Prepare this context for refreshing. //準備作業包括設定啟動時間,是否激活標識位, 初始化屬性源(property source)配置 //不重要 prepareRefresh(); // Tell the subclass to refresh the internal bean factory. //回傳一個factory - 為什么需要回傳一個工廠 //因為要對工廠進行初始化 ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // Prepare the bean factory for use in this context. //為beanFactory設定一些屬性如ClassLoader,BeanExpressionResolver,PropertyEditorRegistrar,BeanPostProcessor等 //準備工廠 prepareBeanFactory(beanFactory); try { // Allows post-processing of the bean factory in context subclasses. //這個方法在當前版本的spring是沒用任何代碼的 //可能spring期待在后面的版本中去擴展吧 postProcessBeanFactory(beanFactory); // Invoke factory processors registered as beans in the context. //為beanFactory注冊BeanFactoryPostProcessor //在spring的環境中去執行已經被注冊的 factory processors //設定執行自定義的ProcessBeanFactory 和spring內部自己定義的 invokeBeanFactoryPostProcessors(beanFactory); // Register bean processors that intercept bean creation. //按照順序注冊當Bean創建時候的BeanPostProcessor //1. 注冊實作了 PriorityOrdered 介面的后置處理器 //2. 注冊實作了 Ordered 介面的后置處理器 //3. 注冊其他的后置處理器 registerBeanPostProcessors(beanFactory); // Initialize message source for this context. //初始化背景關系的訊息源:DelegatingMessageSource initMessageSource(); // Initialize event multicaster for this context. //初始化了一個事件廣播器:SimpleApplicationEventMulticaster initApplicationEventMulticaster(); // Initialize other special beans in specific context subclasses. //空方法, 留著后面擴展用的 onRefresh(); // Check for listener beans and register them. //獲取ApplicationListener,并在事件傳播器中注冊他們 registerListeners(); // Instantiate all remaining (non-lazy-init) singletons. //獲取LoadTimeWeaverAware并初始化他們,初始化單例并且非懶加載的Bean finishBeanFactoryInitialization(beanFactory); // Last step: publish corresponding event. //完成refresh Context操作,初始化LifecycleProcessor并start,發布ContextRefreshedEvent事件 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(); } } }
refresh 方法, 除了 invokeBeanFactoryPostProcessors() 比較重要外, 還有一個很重要的方法: finishBeanFactoryInitialization(beanFactory)
其他的幾個方法, 看看就行, 都是一些注冊, 初始化一些默認屬性什么的, 屬于前期的配置作業.
finishBeanFactoryInitialization
protected void finishBeanFactoryInitialization(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()) { //設定一個內置的型別轉換器 : StringValueResolver beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal)); } // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early. // aspectj的, 基本用不著 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. // 凍結配置 beanFactory.freezeConfiguration(); // Instantiate all remaining (non-lazy-init) singletons. //實體化所有的單例物件 beanFactory.preInstantiateSingletons(); }
preInstantiateSingletons 方法中, 就回去實體化容器里面注冊的 bean.
//org.springframework.beans.factory.support.DefaultListableBeanFactory#preInstantiateSingletons @Override public void preInstantiateSingletons() throws BeansException { if (logger.isTraceEnabled()) { logger.trace("Pre-instantiating singletons in " + this); } //所有bean的名字 // 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); // Trigger initialization of all non-lazy singleton beans... // 觸發所有非延遲加載單例beans的初始化,主要步驟為呼叫getBean for (String beanName : beanNames) { //屬性合并 : 合并父 BeanDefinition, xml中 bean 配置 parent="" RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName); // 非抽象 & 單例 & 非懶加載 if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) { if (isFactoryBean(beanName)) { //如果是FactoryBean則加上& Object bean = getBean(FACTORY_BEAN_PREFIX + beanName); if (bean instanceof FactoryBean) { final FactoryBean<?> factory = (FactoryBean<?>) bean; boolean isEagerInit; if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) { isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>) ((SmartFactoryBean<?>) factory)::isEagerInit, getAccessControlContext()); } else { isEagerInit = (factory instanceof SmartFactoryBean && ((SmartFactoryBean<?>) factory).isEagerInit()); } if (isEagerInit) { getBean(beanName); } } } else { getBean(beanName); } } } // Trigger post-initialization callback for all applicable beans... //當所有的bean都完成創建后, 呼叫他們的 SmartInitializingSingleton 介面的 afterSingletonsInstantiated 方法 for (String beanName : beanNames) { Object singletonInstance = getSingleton(beanName); if (singletonInstance instanceof SmartInitializingSingleton) { final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance; if (System.getSecurityManager() != null) { AccessController.doPrivileged((PrivilegedAction<Object>) () -> { smartSingleton.afterSingletonsInstantiated(); return null; }, getAccessControlContext()); } else { smartSingleton.afterSingletonsInstantiated(); } } } }
這里注意到兩個點:
1. 首先遍歷了容器里面注冊的 beanName , 然后通過 getBean() 的方式, 將 beanName 轉化成 bean.
2. 然后遍歷所有的 bean, 呼叫其 SmartInitializingSingleton#afterSingletonsInstantiated() , 進行最后的初始化呼叫
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/131432.html
標籤:Java
