【Spring源碼分析】非懶加載的單例Bean初始化先後的一些操做

前言html

以前兩篇文章【Spring源碼分析】非懶加載的單例Bean初始化過程(上篇)【Spring源碼分析】非懶加載的單例Bean初始化過程(下篇)比較詳細地分析了非懶加載的單例Bean的初始化過程,整個流程始於AbstractApplicationContext的refresh()方法:spring

public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
        // Prepare this context for refreshing.
        prepareRefresh();

        // Tell the subclass to refresh the internal bean factory.
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

        // Prepare the bean factory for use in this context.
        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) {
            // Destroy already created singletons to avoid dangling resources.
            destroyBeans();

            // Reset 'active' flag.
            cancelRefresh(ex);

            // Propagate exception to caller.
            throw ex;
        }
    }
}

以前重點分析的是finishBeanFactoryInitialization方法,這個方法完成了全部非懶加載的單例Bean的初始化。今天我回頭重看了一下refresh()方法,發現前面有一些方法仍是忽略了沒有去特別在乎,其實他們都是Spring整個啓動流程中的重要組成部分,下面就來分析一下finishBeanFactoryInitialization方法前面的一些方法。app

obtainFreshBeanFactory方法以前已經詳細分析過了,就從prepareBeanFactory方法開始。編輯器

 

PrepareBeanFactory方法ide

看一下PrepareBeanFactory方法的實現:源碼分析

 1 protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
 2     // Tell the internal bean factory to use the context's class loader etc.
 3     beanFactory.setBeanClassLoader(getClassLoader());
 4     beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver());
 5     beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this));
 6 
 7     // Configure the bean factory with context callbacks.
 8     beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
 9     beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
10     beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
11     beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
12     beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
13 
14     // BeanFactory interface not registered as resolvable type in a plain factory.
15     // MessageSource registered (and found for autowiring) as a bean.
16     beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
17     beanFactory.registerResolvableDependency(ResourceLoader.class, this);
18     beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
19     beanFactory.registerResolvableDependency(ApplicationContext.class, this);
20 
21     // Detect a LoadTimeWeaver and prepare for weaving, if found.
22     if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
23         beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
24         // Set a temporary ClassLoader for type matching.
25         beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
26     }
27 
28     // Register default environment beans.
29     if (!beanFactory.containsBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
30         Map systemProperties;
31         try {
32             systemProperties = System.getProperties();
33         }
34         catch (AccessControlException ex) {
35             systemProperties = new ReadOnlySystemAttributesMap() {
36                 @Override
37                 protected String getSystemAttribute(String propertyName) {
38                     try {
39                         return System.getProperty(propertyName);
40                     }
41                     catch (AccessControlException ex) {
42                         if (logger.isInfoEnabled()) {
43                             logger.info("Not allowed to obtain system property [" + propertyName + "]: " +
44                                     ex.getMessage());
45                         }
46                         return null;
47                     }
48                 }
49             };
50         }
51         beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, systemProperties);
52     }
53 
54     if (!beanFactory.containsBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
55         Map<String,String> systemEnvironment;
56         try {
57             systemEnvironment = System.getenv();
58         }
59         catch (AccessControlException ex) {
60             systemEnvironment = new ReadOnlySystemAttributesMap() {
61                 @Override
62                 protected String getSystemAttribute(String variableName) {
63                     try {
64                         return System.getenv(variableName);
65                     }
66                     catch (AccessControlException ex) {
67                         if (logger.isInfoEnabled()) {
68                             logger.info("Not allowed to obtain system environment variable [" + variableName + "]: " +
69                                     ex.getMessage());
70                         }
71                         return null;
72                     }
73                 }
74             };
75         }
76         beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, systemEnvironment);
77     }
78 }

首先是第3行,配置當前上下文ClassLoaderpost

接着是第4行,這是一個表達是語言處理器,可使用#{bean.xxx}的方式來調用相關屬性值測試

接着是第5行,這是一個屬性編輯器,具體沒怎麼用過this

接着是第8行,第8行增長了一個ApplicationContextAwareProcessor用於上下文回調,它是BeanPostProcessor的實現類,跟一下這個接口的兩個方法postProcessBeforeInitialization和postProcessAfterInitialization便可知道這個方法的做用是:spa

  • 若是Bean是EmbeddedValueResolverAware接口的實現類,則調用setEmbeddedValueResolver方法,傳入當前BeanFactory
  • 若是Bean是ResourceLoaderAware接口的實現類,則調用setResourceLoader方法,傳入當前上下文ApplicationContext
  • 若是Bean是ApplicationEventPublisherAware的實現類,則調用setApplicationEventPublisher方法,傳入當前上下文ApplicationContext
  • 若是Bean是MessageSourceAware的實現類,則調用setMessageSource方法,傳入當前上下文ApplicationContext
  • 若是Bean是ApplicationContextAware的實現類,則調用setApplicationContext方法,傳入當前上下文ApplicationContext

接着是第9行~第12行,意思是Bean若是是這些接口的實現類,則不會被自動裝配,自動裝配見【Spring9】Autowire(自動裝配)機制

接着是第16行~第19行,意思是修正依賴,這裏是一些自動裝配的特殊規則,好比是BeanFactory接口的實現類,則修正爲當前BeanFactory

接着是第22行~第26行,意思是若是自定義的Bean中有定義過一個名爲"loadTimeWeaver"的Bean,則會添加一個LoadTimeWeaverAwareProcessor

最後是第29行~第77行,意思是若是自定義的Bean中沒有名爲"systemProperties"和"systemEnvironment"的Bean,則註冊兩個Bena,Key爲"systemProperties"和"systemEnvironment",Value爲Map,這兩個Bean就是一些系統配置和系統環境信息,具體能夠寫這麼一段代碼測試一下:

public class TestSpring {
    
    @SuppressWarnings("unchecked")
    @Test
    public void testSpring() {
        ApplicationContext ac = new ClassPathXmlApplicationContext("spring/spring.xml");
        
        Map<String, String> systemPropertiesBean = (Map<String, String>)ac.getBean("systemProperties");
        for (Map.Entry<String, String> entry : systemPropertiesBean.entrySet()) {
            System.out.println(entry.getKey() + "--->" + entry.getValue());
        }
        
        System.out.println("==============================華麗的分隔符==============================");
        Map<String, String> systemEnvironmentBean = (Map<String, String>)ac.getBean("systemEnvironment");
        for (Map.Entry<String, String> entry : systemEnvironmentBean.entrySet()) {
            System.out.println(entry.getKey() + "--->" + entry.getValue());
        }
    }
    
}

涉及我的信息,運行結果我就不貼了,你們能夠本身試試,至此整個PrepareBeanFactory方法的細節已經分析完畢了。

 

invokeBeanFactoryPostProcessors方法

這個是整個Spring流程中很是重要的一部分,是Spring留給用戶的一個很是有用的擴展點,BeanPostProcessor接口針對的是每一個Bean初始化先後作的操做而BeanFactoryPostProcessor接口針對的是全部Bean實例化前的操做,注意用詞,初始化只是實例化的一部分,表示的是調用Bean的初始化方法,BeanFactoryPostProcessor接口方法調用時機是任意一個自定義的Bean被反射生成出來前

OK,看一下源碼:

 1 protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
 2     // Invoke BeanDefinitionRegistryPostProcessors first, if any.
 3     Set<String> processedBeans = new HashSet<String>();
 4     if (beanFactory instanceof BeanDefinitionRegistry) {
 5         BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
 6         List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
 7         List<BeanDefinitionRegistryPostProcessor> registryPostProcessors =
 8                 new LinkedList<BeanDefinitionRegistryPostProcessor>();
 9         for (BeanFactoryPostProcessor postProcessor : getBeanFactoryPostProcessors()) {
10             if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
11                 BeanDefinitionRegistryPostProcessor registryPostProcessor =
12                             (BeanDefinitionRegistryPostProcessor) postProcessor;
13                     registryPostProcessor.postProcessBeanDefinitionRegistry(registry);
14                     registryPostProcessors.add(registryPostProcessor);
15             }
16             else {
17                 regularPostProcessors.add(postProcessor);
18             }
19         }
20         Map<String, BeanDefinitionRegistryPostProcessor> beanMap =
21                 beanFactory.getBeansOfType(BeanDefinitionRegistryPostProcessor.class, true, false);
22         List<BeanDefinitionRegistryPostProcessor> registryPostProcessorBeans =
23                 new ArrayList<BeanDefinitionRegistryPostProcessor>(beanMap.values());
24         OrderComparator.sort(registryPostProcessorBeans);
25         for (BeanDefinitionRegistryPostProcessor postProcessor : registryPostProcessorBeans) {
26             postProcessor.postProcessBeanDefinitionRegistry(registry);
27         }
28         invokeBeanFactoryPostProcessors(registryPostProcessors, beanFactory);
29         invokeBeanFactoryPostProcessors(registryPostProcessorBeans, beanFactory);
30         invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
31         processedBeans.addAll(beanMap.keySet());
32     }
33     else {
34         // Invoke factory processors registered with the context instance.
35         invokeBeanFactoryPostProcessors(getBeanFactoryPostProcessors(), beanFactory);
36     }
37 
38     // Do not initialize FactoryBeans here: We need to leave all regular beans
39     // uninitialized to let the bean factory post-processors apply to them!
40     String[] postProcessorNames =
41         beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
42 
43     // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
44     // Ordered, and the rest.
45     List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
46     List<String> orderedPostProcessorNames = new ArrayList<String>();
47     List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
48     for (String ppName : postProcessorNames) {
49         if (processedBeans.contains(ppName)) {
50             // skip - already processed in first phase above
51         }
52         else if (isTypeMatch(ppName, PriorityOrdered.class)) {
53             priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
54         }
55         else if (isTypeMatch(ppName, Ordered.class)) {
56             orderedPostProcessorNames.add(ppName);
57         }
58         else {
59             nonOrderedPostProcessorNames.add(ppName);
60         }
61     }
62 
63     // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
64     OrderComparator.sort(priorityOrderedPostProcessors);
65     invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
66 
67     // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
68     List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
69     for (String postProcessorName : orderedPostProcessorNames) {
70         orderedPostProcessors.add(getBean(postProcessorName, BeanFactoryPostProcessor.class));
71     }
72     OrderComparator.sort(orderedPostProcessors);
73     invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
74 
75     // Finally, invoke all other BeanFactoryPostProcessors.
76     List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
77     for (String postProcessorName : nonOrderedPostProcessorNames) {
78         nonOrderedPostProcessors.add(getBean(postProcessorName, BeanFactoryPostProcessor.class));
79     }
80     invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
81 }

咱們能夠本身實現BeanFactoryPostProcessor接口並實現postProcessBeanFactory方法,在全部Bean加載的流程開始前,會調用一次postProcessBeanFactory方法。分析一下這段代碼,首先咱們使用的是DefaultListableBeanFactory,它是BeanDefinitionRegistry的子類,所以進入第4行的判斷。

整個判斷獲取的是當前有的BeanFactoryPostProcessor並調用postProcessBeanFactory,這些BeanFactoryPostProcessor是前置經過AbstractApplicationContext的addBeanFactoryPostProcessor方法添加的而不是配置文件裏面配置的BeanFactoryPostProcessor的實現Bean,所以這個判斷沒有任何可執行的BeanFactoryPostProcessor。

接着40行~41行這兩行,獲取的是beanDefinitionMap中的Bean,即用戶自定義的Bean。

接着第45行~61行,這裏分出了三個List,表示開發者能夠自定義BeanFactoryPostProcessor的調用順序,具體爲調用順序爲:

  • 若是BeanFactoryPostProcessor實現了PriorityOrdered接口(PriorityOrdered接口是Ordered的子接口,沒有本身的接口方法定義,只是作一個標記,表示調用優先級高於Ordered接口的子接口),是優先級最高的調用,調用順序是按照接口方法getOrder()的實現,對返回的int值從小到大進行排序,進行調用
  • 若是BeanFactoryPostProcessor實現了Ordered接口,是優先級次高的調用,將在全部實現PriorityOrdered接口的BeanFactoryPostProcessor調用完畢以後,依據getOrder()的實現對返回的int值從小到大排序,進行調用
  • 不實現Ordered接口的BeanFactoryPostProcessor在上面的BeanFactoryPostProcessor調用所有完畢以後進行調用,調用順序就是Bean定義的順序

最後的第63行~第80行就是按照上面的規則依次先將BeanFactoryPostProcessor接口對應的實現類實例化出來並調用postProcessBeanFactory方法。

 

registerBeanPostProcessors方法

接下來看看registerBeanPostProcessors方法,顧名思義,就是註冊自定義的BeanPostProcessor接口。看一下代碼實現:

 1 protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
 2     String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
 3 
 4     // Register BeanPostProcessorChecker that logs an info message when
 5     // a bean is created during BeanPostProcessor instantiation, i.e. when
 6     // a bean is not eligible for getting processed by all BeanPostProcessors.
 7     int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
 8     beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
 9 
10     // Separate between BeanPostProcessors that implement PriorityOrdered,
11     // Ordered, and the rest.
12     List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
13     List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>();
14     List<String> orderedPostProcessorNames = new ArrayList<String>();
15     List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
16     for (String ppName : postProcessorNames) {
17         if (isTypeMatch(ppName, PriorityOrdered.class)) {
18             BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
19             priorityOrderedPostProcessors.add(pp);
20             if (pp instanceof MergedBeanDefinitionPostProcessor) {
21                 internalPostProcessors.add(pp);
22             }
23         }
24         else if (isTypeMatch(ppName, Ordered.class)) {
25             orderedPostProcessorNames.add(ppName);
26         }
27         else {
28             nonOrderedPostProcessorNames.add(ppName);
29         }
30     }
31 
32     // First, register the BeanPostProcessors that implement PriorityOrdered.
33     OrderComparator.sort(priorityOrderedPostProcessors);
34     registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
35 
36     // Next, register the BeanPostProcessors that implement Ordered.
37     List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>();
38     for (String ppName : orderedPostProcessorNames) {
39         BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
40         orderedPostProcessors.add(pp);
41         if (pp instanceof MergedBeanDefinitionPostProcessor) {
42             internalPostProcessors.add(pp);
43         }
44     }
45     OrderComparator.sort(orderedPostProcessors);
46     registerBeanPostProcessors(beanFactory, orderedPostProcessors);
47 
48     // Now, register all regular BeanPostProcessors.
49     List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>();
50     for (String ppName : nonOrderedPostProcessorNames) {
51         BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
52         nonOrderedPostProcessors.add(pp);
53         if (pp instanceof MergedBeanDefinitionPostProcessor) {
54             internalPostProcessors.add(pp);
55         }
56     }
57     registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
58 
59     // Finally, re-register all internal BeanPostProcessors.
60     OrderComparator.sort(internalPostProcessors);
61     registerBeanPostProcessors(beanFactory, internalPostProcessors);
62 
63     beanFactory.addBeanPostProcessor(new ApplicationListenerDetector());
64 }

總體代碼思路和invokeBeanFactoryPostProcessors方法相似,可是這裏不會調用BeanPostProcessor接口的方法,而是把每個BeanPostProcessor接口實現類實例化出來並按照順序放入一個List中,到時候按順序進行調用。

具體代碼思路能夠參考invokeBeanFactoryPostProcessors,這裏就根據代碼總結一下BeanPostProcessor接口的調用順序:

  • 優先調用PriorityOrdered接口的子接口,調用順序依照接口方法getOrder的返回值從小到大排序
  • 其次調用Ordered接口的子接口,調用順序依照接口方法getOrder的返回值從小到大排序
  • 接着按照BeanPostProcessor實現類在配置文件中定義的順序進行調用
  • 最後調用MergedBeanDefinitionPostProcessor接口的實現Bean,一樣按照在配置文件中定義的順序進行調用

 

initMessageSource方法

initMessageSource方法用於初始化MessageSource,MessageSource是Spring定義的用於實現訪問國際化的接口,看一下源碼:

 1 protected void initMessageSource() {
 2     ConfigurableListableBeanFactory beanFactory = getBeanFactory();
 3     if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
 4         this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
 5         // Make MessageSource aware of parent MessageSource.
 6         if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
 7             HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
 8             if (hms.getParentMessageSource() == null) {
 9                 // Only set parent context as parent MessageSource if no parent MessageSource
10                 // registered already.
11                 hms.setParentMessageSource(getInternalParentMessageSource());
12             }
13         }
14         if (logger.isDebugEnabled()) {
15             logger.debug("Using MessageSource [" + this.messageSource + "]");
16         }
17     }
18     else {
19         // Use empty MessageSource to be able to accept getMessage calls.
20         DelegatingMessageSource dms = new DelegatingMessageSource();
21         dms.setParentMessageSource(getInternalParentMessageSource());
22         this.messageSource = dms;
23             beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
24         if (logger.isDebugEnabled()) {
25             logger.debug("Unable to locate MessageSource with name '" + MESSAGE_SOURCE_BEAN_NAME +
26                     "': using default [" + this.messageSource + "]");
27         }
28     }
29 }

這個if...else...判斷比較好理解:

  • 若是自定義了名爲"messageSource"的Bean,那麼直接實例化Bean,該Bean必須是MessageSource接口的實現Bean,順便該Bean若是是HierarchicalMessageSource接口的實現類,強轉爲HierarchicalMessageSource接口,並設置一下parentMessageSource
  • 若是沒有自定義名爲"messageSource"的Bean,那麼會默認註冊一個DelegatingMessageSource並加入

 

initApplicationEventMulticaster方法

initApplicationEventMulticaster方法是用於初始化上下文事件廣播器的,看一下源碼:

 1 protected void initApplicationEventMulticaster() {
 2     ConfigurableListableBeanFactory beanFactory = getBeanFactory();
 3     if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
 4         this.applicationEventMulticaster =
 5                 beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
 6         if (logger.isDebugEnabled()) {
 7             logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
 8         }
 9     }
10     else {
11         this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
12         beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
13         if (logger.isDebugEnabled()) {
14             logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
15                     APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
16                     "': using default [" + this.applicationEventMulticaster + "]");
17         }
18     }
19 }

和initMessageSource方法同樣,這個if...else...判斷也比較好理解:

  • 若是自定義了名爲"applicationEventMulticaster"的Bean,就實例化自定義的Bean,但自定義的Bean必須是ApplicationEventMulticaster接口的實現類
  • 若是沒有自定義名爲"ApplicationEventMulticaster"的Bean,那麼就註冊一個類型爲SimpleApplicationEventMulticaster的Bean

整個Spring的廣播器是觀察者模式的經典應用場景之一,這個以後有時間會分析Spring廣播器的源碼。

 

onRefresh方法

接下來簡單說說onRefresh方法,AbstractApplicationContext中這個方法沒有什麼定義:

/**
 * 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()
 */
protected void onRefresh() throws BeansException {
    // For subclasses: do nothing by default.
}

看一下注釋的意思:一個模板方法,重寫它的做用是添加特殊上下文刷新的工做,在特殊Bean的初始化時、初始化以前被調用。在Spring中,AbstractRefreshableWebApplicationContext、GenericWebApplicationContext、StaticWebApplicationContext都實現了這個方法。

 

registerListeners方法

registerListeners方法顧名思義,用於註冊監聽器:

 1 /**
 2  * Add beans that implement ApplicationListener as listeners.
 3  * Doesn't affect other listeners, which can be added without being beans.
 4  */
 5 protected void registerListeners() {
 6     // Register statically specified listeners first.
 7     for (ApplicationListener listener : getApplicationListeners()) {
 8         getApplicationEventMulticaster().addApplicationListener(listener);
 9     }
10     // Do not initialize FactoryBeans here: We need to leave all regular beans
11     // uninitialized to let post-processors apply to them!
12     String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
13     for (String lisName : listenerBeanNames) {
14         getApplicationEventMulticaster().addApplicationListenerBean(lisName);
15     }
16 }

這裏先向applicationEventMulticaster中註冊一些靜態的、特定的監聽器。

 

finishRefresh方法

最後一步,結束Spring上下文刷新:

 1 /**
 2  * Finish the refresh of this context, invoking the LifecycleProcessor's
 3  * onRefresh() method and publishing the
 4  * {@link org.springframework.context.event.ContextRefreshedEvent}.
 5  */
 6 protected void finishRefresh() {
 7     // Initialize lifecycle processor for this context.
 8     initLifecycleProcessor();
 9 
10     // Propagate refresh to lifecycle processor first.
11     getLifecycleProcessor().onRefresh();
12 
13     // Publish the final event.
14     publishEvent(new ContextRefreshedEvent(this));
15 }

這裏面分了三步,第一步,初始化LifecycleProcessor接口:

 1 protected void initLifecycleProcessor() {
 2     ConfigurableListableBeanFactory beanFactory = getBeanFactory();
 3     if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
 4         this.lifecycleProcessor =
 5                 beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
 6         if (logger.isDebugEnabled()) {
 7             logger.debug("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
 8         }
 9     }
10     else {
11         DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
12         defaultProcessor.setBeanFactory(beanFactory);
13         this.lifecycleProcessor = defaultProcessor;
14         beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
15         if (logger.isDebugEnabled()) {
16             logger.debug("Unable to locate LifecycleProcessor with name '" +
17                     LIFECYCLE_PROCESSOR_BEAN_NAME +
18                     "': using default [" + this.lifecycleProcessor + "]");
19         }
20     }
21 }

流程和initMessageSource方法、initApplicationEventMulticaster方法基本相似:

  • 先找一下有沒有自定義名爲"lifecycleProcessor"的Bean,有的話就實例化出來,該Bean必須是LifecycleProcessor的實現類
  • 沒有自定義名爲"lifecycleProcessor"的Bean,向Spring上下文中註冊一個類型爲DefaultLifecycleProcessor的LifecycleProcessor實現類

第二步,調用一下LifecycleProcessor的onRefresh方法。

第三步,因爲以前已經初始化了:

 1 public void publishEvent(ApplicationEvent event) {
 2     Assert.notNull(event, "Event must not be null");
 3     if (logger.isTraceEnabled()) {
 4         logger.trace("Publishing event in " + getDisplayName() + ": " + event);
 5     }
 6     getApplicationEventMulticaster().multicastEvent(event);
 7     if (this.parent != null) {
 8         this.parent.publishEvent(event);
 9     }
10 }

 

後記

再看AbstractApplicationContext的refresh方法,從中讀到了不少細節:

  • Spring默認加載的兩個Bean,systemProperties和systemEnvironment,分別用於獲取環境信息、系統信息
  • BeanFactoryPostProcessor接口用於在全部Bean實例化以前調用一次postProcessBeanFactory
  • 能夠經過實現PriorityOrder、Order接口控制BeanFactoryPostProcessor調用順序
  • 能夠經過實現PriorityOrder、Order接口控制BeanPostProcessor調用順序
  • 默認的MessageSource,名爲"messageSource"
  • 默認的ApplicationEventMulticaster,名爲"applicationEventMulticaster"
  • 默認的LifecycleProcessor,名爲"lifecycleProcessor"

除了這些,在整個refresh方法裏還隱藏了許多細節,這裏就不一一羅列了,多讀源碼,會幫助咱們更好地使用Spring。

相關文章
相關標籤/搜索