xml地图|网站地图|网站标签 [设为首页] [加入收藏]

源码解析,Bean生命周期

来源:http://www.ccidsi.com 作者:最新解决方案 人气:125 发布时间:2020-01-15
摘要:ApplicationContext刷新的时候上一步提到了,先调用BeanFactoryPostProcessors预管理下BeanFactory,未来注册Beanprocessors来堵住Bean的成立。 【Spring源码解析】非懒加载的单例Bean开端化前后的局部操

ApplicationContext刷新的时候上一步提到了,先调用BeanFactoryPostProcessors预管理下BeanFactory,未来注册Bean processors来堵住Bean的成立。

【Spring源码解析】非懒加载的单例Bean开端化前后的局部操作,springbean

前言

事情发生前两篇作品【Spring源码解析】非懒加载的单例Bean最早化进度(上篇)和【Spring源码剖析】非懒加载的单例Bean初步化进程(下篇)相比详细地剖析了非懒加载的单例Bean的早先化进程,整个流程始于AbstractApplicationContext的refresh(卡塔尔国方法:

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方法前边的片段艺术。

obtainFreshBeanFactory方法此前曾经详细解析过了,就从prepareBeanFactory方法伊始。

 

'PrepareBeanFactory方法

看一下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行,配置当前上下文ClassLoader

随着是第4行,那是一个表述是语言微处理机,能够接收#{bean.xxx}的主意来调用相关属性值

随就是第5行,那是八个天性编辑器,具体没怎么用过

随着是第8行,第8行扩大了二个ApplicationContextAwareProcessor用于上下文回调,它是BeanPostProcessor的落到实处类,跟一下这一个接口的多少个章程postProcessBeforeInitialization和postProcessAfterInitialization就可以以见到道那几个艺术的功力是:

  • 若果Bean是EmbeddedValueResolverAware接口的落实类,则调用setEmbeddedValueResolver方法,传入当前BeanFactory
  • 如果Bean是ResourceLoaderAware接口的兑现类,则调用setResourceLoader方法,传入当前上下文ApplicationContext
  • 少年老成旦Bean是ApplicationEventPublisherAware的兑现类,则调用setApplication伊夫ntPublisher方法,传入当前上下文ApplicationContext
  • 若是Bean是MessageSourceAware的达成类,则调用setMessageSource方法,传入当前上下文ApplicationContext
  • 比如Bean是ApplicationContextAware的落成类,则调用setApplicationContext方法,传入当前上下文ApplicationContext

随着是第9行~第12行,意思是Bean假若是那一个接口的完成类,则不会被电动注入

随之是第16行~第19行,意思是纠正重视,这里是局地机关装配的独特法规,譬喻是BeanFactory接口的达成类,则改正为日前BeanFactory

紧接着是第22行~第26行,意思是只要自定义的Bean中并未有一个名字为"loadTimeWeaver"的Bena,则会增多一个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(State of Qatar的贯彻,对回到的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必得是Application伊夫ntMulticaster接口的兑现类
  • 意气风发旦未有自定义名称叫"Application伊夫ntMulticaster"的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 }

此间先向application伊夫ntMulticaster中登记一些静态的、特定的监听器。

 

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方法、initApplication伊芙ntMulticaster方法基本贴近:

  • 先找一下有未有自定义名称为"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。

前言 从前两篇小说【Spring源码解析】非懒加载的单例Bean初阶化进程...

请尊重作者劳动成果,转发请标记原来的小说链接:

实例化,然后调用全部注册的BeanPostProcessor bean。即使钦命了逐意气风发,会依据顺序试行。必需在应用Bean实例化在此以前调用。

上生龙活虎篇深入分析了SpringApplication的run方法的意气风发有的,接下去继续剖析剩下的一些

protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) { PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this); }
 1 public ConfigurableApplicationContext run(String... args) {
 2     StopWatch stopWatch = new StopWatch();
 3     stopWatch.start();
 4     ConfigurableApplicationContext context = null;
 5     FailureAnalyzers analyzers = null;
 6     configureHeadlessProperty();
 7     SpringApplicationRunListeners listeners = getRunListeners(args);
 8     listeners.starting();
 9     try {
10         ApplicationArguments applicationArguments = new DefaultApplicationArguments(
11                 args);
12         ConfigurableEnvironment environment = prepareEnvironment(listeners,
13                 applicationArguments);
14         Banner printedBanner = printBanner(environment);
15         context = createApplicationContext();
16         analyzers = new FailureAnalyzers(context);
17         prepareContext(context, environment, listeners, applicationArguments,
18                 printedBanner);
19         refreshContext(context);
20         afterRefresh(context, applicationArguments);
21         listeners.finished(context, null);
22         stopWatch.stop();
23         if (this.logStartupInfo) {
24             new StartupInfoLogger(this.mainApplicationClass)
25                     .logStarted(getApplicationLog(), stopWatch);
26         }
27         return context;
28     }
29     catch (Throwable ex) {
30         handleRunFailure(context, listeners, analyzers, ex);
31         throw new IllegalStateException(ex);
32     }
33 }

分析

先见到如故那几个工具类,在上步的BeanFactoryPostProcessors中采纳的也是它。

图片 1image.png

注册BeanPostProcessor的代码如下:

 public static void registerBeanPostProcessors( ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) { // 获取BeanFactory中注册的类型为BeanPostProcessor.class的bean名称。一般获取到的是实现了BeanPostProcessor接口的Bean String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false); // 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. // 注册一个BeanPostProcessorChecker,用来记录bean在BeanPostProcessor实例化时的信息。 int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount()   1   postProcessorNames.length; beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount)); // Separate between BeanPostProcessors that implement PriorityOrdered, // Ordered, and the rest. // 将BeanPostProcessors分为实现了PriorityOrdered,Ordered等类型 List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanPostProcessor>(); List<BeanPostProcessor> internalPostProcessors = new ArrayList<BeanPostProcessor>(); List<String> orderedPostProcessorNames = new ArrayList<String>(); List<String> nonOrderedPostProcessorNames = new ArrayList<String>(); for (String ppName : postProcessorNames) { if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); priorityOrderedPostProcessors.add; // 如果BeanPostProcessors也实现了MergedBeanDefinitionPostProcessor接口,加入internalPostProcessors if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add; } } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add; } else { nonOrderedPostProcessorNames.add; } } // First, register the BeanPostProcessors that implement PriorityOrdered. // 首先注册实现了PriorityOrdered接口的BeanPostProcessors sortPostProcessors(beanFactory, priorityOrderedPostProcessors); registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); // Next, register the BeanPostProcessors that implement Ordered. // 然后,注册实现了Ordered的BeanPostProcessors List<BeanPostProcessor> orderedPostProcessors = new ArrayList<BeanPostProcessor>(); for (String ppName : orderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); orderedPostProcessors.add; if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add; } } sortPostProcessors(beanFactory, orderedPostProcessors); registerBeanPostProcessors(beanFactory, orderedPostProcessors); // Now, register all regular BeanPostProcessors. // 现在注册所有常规的BeanPostProcessors List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanPostProcessor>(); for (String ppName : nonOrderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); nonOrderedPostProcessors.add; if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add; } } registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors); // Finally, re-register all internal BeanPostProcessors. // 最后注册,所有的internal,也就是实现MergedBeanDefinitionPostProcessor的BeanPostProcessors sortPostProcessors(beanFactory, internalPostProcessors); registerBeanPostProcessors(beanFactory, internalPostProcessors); //添加ApplicationListenerDetector的BeanPostProcessor beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext)); }

全部代码也简单了解,如函数名,正是做了挂号BeanPostProcessor

  • 得到完毕了BeanPostProcessor的bean Name,最领头Bean的信息注册到了beandifinitionMap中
  • 将取获得的BeanPostProcessor分类,分为PriorityOrdered,Ordered和健康的门类
  • 分级将PriorityOrdered,Ordered和符合规律的Bean加多进ApplicationContext的beanPostProcessors中,ApplicationContext的beanPostProcessors是ArrayList。

第19行调用refreshContext方法,refreshContext方法又调用了refresh方法,而refresh方法又调用了context父类AbstractApplicationContext(真正的完毕类是EmbeddedWebApplicationContext)的refresh方法,接着又调用AbstractApplicationContext的refresh方法

BeanFactory.getBeanNamesForType具体得以达成

当中间调用的是doGetBeanNamesForType

  • 遍历beanDefinitionNames推断是还是不是切合供给是不是为type
  • 遍历manualSingletonNames。

里面有个管理是要是Bean是FactoryBean,其名称前边加上&

private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit){ // Check all bean definitions. // 检查所有的beanDefinitionNames。 for (String beanName : this.beanDefinitionNames) { // Only consider bean as eligible if the bean name // is not defined as alias for some other bean. if (!isAlias) { try { RootBeanDefinition mbd = getMergedLocalBeanDefinition; // Only check bean definition if it is complete. if (!mbd.isAbstract() && (allowEagerInit || ((mbd.hasBeanClass() || !mbd.isLazyInit() || isAllowEagerClassLoading && !requiresEagerInitForType(mbd.getFactoryBeanName { // In case of FactoryBean, match object created by FactoryBean. boolean isFactoryBean = isFactoryBean(beanName, mbd); boolean matchFound = (allowEagerInit || !isFactoryBean || containsSingleton) && (includeNonSingletons || isSingleton) && isTypeMatch(beanName, type); if (!matchFound && isFactoryBean) { // In case of FactoryBean, try to match FactoryBean instance itself next. beanName = FACTORY_BEAN_PREFIX   beanName; matchFound = (includeNonSingletons || mbd.isSingleton && isTypeMatch(beanName, type); } if (matchFound) { result.add; } } } .... } // Check manually registered singletons too. for (String beanName : this.manualSingletonNames) { try { // In case of FactoryBean, match object created by FactoryBean. if (isFactoryBean) { if ((includeNonSingletons || isSingleton) && isTypeMatch(beanName, type)) { result.add; // Match found for this bean: do not match FactoryBean itself anymore. continue; } // In case of FactoryBean, try to match FactoryBean itself next. beanName = FACTORY_BEAN_PREFIX   beanName; } // Match raw bean instance (might be raw FactoryBean). if (isTypeMatch(beanName, type)) { result.add; } } ... } return StringUtils.toStringArray;}

AbstractApplicationContext的refresh方法是本篇深入分析的要害,倘让你通过ApplicationContext apc = new ClassPathXmlApplicationContext("beans.xml"卡塔尔;的措施运行Spring,也是会调用那么些refresh方法来初阶化容器的,它根本是完毕配置类的深入分析,种种BeanFactoryPostProcessor和BeanPostProcessor的挂号,内置容器(tomcat卡塔尔(قطر‎布局,国际化结构早先化,实例化非延迟加载的单例bean等

TODO

  • BeanFactory中beanDefinitionNames,manualSingletonNames等属性深切精晓
 1 @Override
 2 public void refresh() throws BeansException, IllegalStateException {
 3     synchronized (this.startupShutdownMonitor) {
 4         // Prepare this context for refreshing.
 5         prepareRefresh();
 6 
 7         // Tell the subclass to refresh the internal bean factory.
 8         ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
 9 
10         // Prepare the bean factory for use in this context.
11         prepareBeanFactory(beanFactory);
12 
13         try {
14             // Allows post-processing of the bean factory in context subclasses.
15             postProcessBeanFactory(beanFactory);
16 
17             // Invoke factory processors registered as beans in the context.
18             invokeBeanFactoryPostProcessors(beanFactory);
19 
20             // Register bean processors that intercept bean creation.
21             registerBeanPostProcessors(beanFactory);
22 
23             // Initialize message source for this context.
24             initMessageSource();
25 
26             // Initialize event multicaster for this context.
27             initApplicationEventMulticaster();
28 
29             // Initialize other special beans in specific context subclasses.
30             onRefresh();
31 
32             // Check for listener beans and register them.
33             registerListeners();
34 
35             // Instantiate all remaining (non-lazy-init) singletons.
36             finishBeanFactoryInitialization(beanFactory);
37 
38             // Last step: publish corresponding event.
39             finishRefresh();
40         }
41 
42         catch (BeansException ex) {
43             if (logger.isWarnEnabled()) {
44                 logger.warn("Exception encountered during context initialization - "  
45                         "cancelling refresh attempt: "   ex);
46             }
47 
48             // Destroy already created singletons to avoid dangling resources.
49             destroyBeans();
50 
51             // Reset 'active' flag.
52             cancelRefresh(ex);
53 
54             // Propagate exception to caller.
55             throw ex;
56         }
57 
58         finally {
59             // Reset common introspection caches in Spring's core, since we
60             // might not ever need metadata for singleton beans anymore...
61             resetCommonCaches();
62         }
63     }
64 }

最后

注册BeanPostProcessor和invokeBeanFactoryPostProcessors很像,並且没什么复杂逻辑。正是将已经注册到beanFacory的Bean筛选出BeanPostProcessor然后增添到ApplicationContext的beanPostProcessor集结中。

第3行使用synchronized关键字得到startupShutdownMonitor的锁,close方法的首先行也是先拿到该锁,表明运转容器和关闭容器都以同步操作的,是线程安全的

第5行调用prepareRefresh方法,该措施首假使做些策画干活,举个例子清空缓存,记录容器运营的时日,设置closed为false,设置active为true,初始化属性消息,验证供给的习性

那边的初阶化属性音信和认证要求的天性方法暗中认可是不做任何事情的,但一时系统运营要求读取某个系统品质,未有这一个属性,系统将运营不健康,此时,在开创容器以前就要对那么些必需的脾气做个注解,比方自身达成叁个ApplicationContext并覆盖initPropertySources方法

1 public class MyApplicationContext extends AnnotationConfigEmbeddedWebApplicationContext {
2     protected void initPropertySources() {
3         getEnvironment().setRequiredProperties("dylan.required");
4     }
5 }

然后SpringApplication运行的艺术也改下

1 @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class})
2 public class Application {
3     public static void main(String[] args) {
4         SpringApplication springApplication = new SpringApplication(new Object[] {Application.class});
5         springApplication.setApplicationContextClass(MyApplicationContext.class);
6         springApplication.run(args);
7     }
8 }

那么当运维到initPropertySources(卡塔尔;这么些点羊时,会调用自定义的ApplicationContext的initPropertySources方法,向environment中增添供给的品质,而运作getEnvironment(State of Qatar.validateRequiredProperties(卡塔尔国;这一个措施的时候,就能够检讨是否配备了"dylan.required"属性,若无安插,那么会抛出特别,容器运维战败

第8行通过obtainFreshBeanFactory方法取获得beanFactory

1 protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
2     refreshBeanFactory();
3     ConfigurableListableBeanFactory beanFactory = getBeanFactory();
4     if (logger.isDebugEnabled()) {
5         logger.debug("Bean factory for "   getDisplayName()   ": "   beanFactory);
6     }
7     return beanFactory;
8 }

refreshBeanFactory方法把refreshed属性设置成true,表示已经刷新了,下次再刷新就能抛出分外,差别意再一次刷新,然后给beanFactory设置serializationId,就是前面经过ContextIdApplicationContextInitializer生成的id

getBeanFactory方法获得ApplicationContext的beanFactory(从前创立上下文的时候,也等于调用createApplicationContext方法,GenericApplicationContext的布局函数里会实例化一个DefaultListableBeanFactory对象卡塔尔国,然后回来

1 public GenericApplicationContext() {
2     this.beanFactory = new DefaultListableBeanFactory();
3 }

第11行调用prepareBeanFactory方法,该措施对beanFactory进行生龙活虎密密层层的安装

 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(beanFactory.getBeanClassLoader()));
 5     beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
 6 
 7     // Configure the bean factory with context callbacks.
 8     beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
 9     beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
10     beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
11     beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
12     beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
13     beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
14     beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
15 
16     // BeanFactory interface not registered as resolvable type in a plain factory.
17     // MessageSource registered (and found for autowiring) as a bean.
18     beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
19     beanFactory.registerResolvableDependency(ResourceLoader.class, this);
20     beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
21     beanFactory.registerResolvableDependency(ApplicationContext.class, this);
22 
23     // Register early post-processor for detecting inner beans as ApplicationListeners.
24     beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
25 
26     // Detect a LoadTimeWeaver and prepare for weaving, if found.
27     if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
28         beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
29         // Set a temporary ClassLoader for type matching.
30         beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
31     }
32 
33     // Register default environment beans.
34     if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
35         beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
36     }
37     if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
38         beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
39     }
40     if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
41         beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
42     }
43 }

率先设置用于加载bean的类加载器,再安装能够剖析bean表明式的表明式深入解析器(使用"#{xxx}"配置的属性State of Qatar,然后加多属性注册器,并加多了一个BeanPostProcessor - ApplicationContextAwareProcessor的实例

进而设置了6个忽视自动注入的接口(EnvironmentAware、EmbeddedValueResolverAware、ResourceLoaderAware、ApplicationEventPublisherAware、MessageSourceAware、ApplicationContextAwareState of Qatar,为何要不经意呢?因为上一步增加的BeanPostProcessor - ApplicationContextAwareProcessor,BeanPostProcessor会在会在bean早先化前后调用相应的主意,大家看一下ApplicationContextAwareProcessor的代码

 1 @Override
 2 public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
 3     AccessControlContext acc = null;
 4 
 5     if (System.getSecurityManager() != null &&
 6             (bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
 7                     bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
 8                     bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
 9         acc = this.applicationContext.getBeanFactory().getAccessControlContext();
10     }
11 
12     if (acc != null) {
13         AccessController.doPrivileged(new PrivilegedAction<Object>() {
14             @Override
15             public Object run() {
16                 invokeAwareInterfaces(bean);
17                 return null;
18             }
19         }, acc);
20     }
21     else {
22         invokeAwareInterfaces(bean);
23     }
24 
25     return bean;
26 }
27 
28 private void invokeAwareInterfaces(Object bean) {
29     if (bean instanceof Aware) {
30         if (bean instanceof EnvironmentAware) {
31             ((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
32         }
33         if (bean instanceof EmbeddedValueResolverAware) {
34             ((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
35         }
36         if (bean instanceof ResourceLoaderAware) {
37             ((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
38         }
39         if (bean instanceof ApplicationEventPublisherAware) {
40             ((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
41         }
42         if (bean instanceof MessageSourceAware) {
43             ((MessageSourceAware) bean).setMessageSource(this.applicationContext);
44         }
45         if (bean instanceof ApplicationContextAware) {
46             ((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
47         }
48     }
49 }

从地点浅蓝证明的代码能够看见,在ApplicationContextAwareProcessor的postProcessBeforeInitialization方法里适逢其会帮大家做了那6个被忽视的Aware接口存在感知的动作

接下去的4行设置了多少个电动装配的非凡法则,假诺流入的是BeanFactory类型,则注入beanFactory对象,假诺是ResourceLoader、ApplicationEventPublisher、ApplicationContext类型,则注入当前目的(Spring上下文

  • context)

下一场又报了名了一个BeanPostProcessor - ApplicationListenerDetector,我们看下ApplicationListenerDetector的代码

本文由68399皇家赌场发布于最新解决方案,转载请注明出处:源码解析,Bean生命周期

关键词: 68399皇家赌场 生命周期 spring Bean SpringBoot

上一篇:根文件系统,Linux目录结构

下一篇:没有了

最火资讯