本文共 2355 字,大约阅读时间需要 7 分钟。
bean 实在 bean 刷新过程中产生的,首先我们看下 bean 的刷新方法。下面是 AbstractApplicationContext 的 refresh 方法。
@Override 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) { 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(); } } }
我们可以看到这个方法中一共进行了准备刷新,获取bean工厂,调用 postProcess 等一系列操作。
这里有一个比较重要的地方就是 postProcess 是什么东西
熟悉 spring 的应该都知道,postProcessor给 用户留的一个扩展点,Spring允许BeanFactoryPostProcessor在容器实例化前后操纵 bean 的属性,BeanPostProcessor实现类可以在bean初始化前后做一些事情,BeanPostProcessor的作用域是容器级的,它只和所在容器有关。
bean 的默认生成就是通过默认的 postProcessor 生成的。bean 的生成主要分为通过注解,通过xml,通过自动扫描,以及mybatis dao的bean生成,这些每一种类型都是一种bean的生成器,当然,我们也可以自定义我们自己的 bean 生成器。
bean 生成以后被保存在一个map里,用来供调用。
初看 spring 源码,难免理解错误,希望大家能指出和谅解,感激不尽。
转载地址:http://lkwtb.baihongyu.com/