SpringIOC——refresh()
一、refresh()方法
使用模板方法模式定义的一个顶级抽象父类,方法具体实现延迟到子类 ,每一个方法都是一个钩子,可以被子类重写。
@Override public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { // ② IOC初始化前的装备(配置环境参数、创建监听器、事件容器) prepareRefresh(); // ③ 这里可以分为两类:
// GenericApplicationContext: 仅仅是控制beanfactory不能重复refresh
// AbstractRefreshableApplicationContext:允许重复refresh,销毁就beanfactory,创建新beanfactory并且重新扫描生成beanDefinitionMap容器。
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // ④ 设置beanfactory的一些属性(bean的类加载器、忽略接口、BeanPostProcessor、环境参数单例注册到beanfactory单例容器中) prepareBeanFactory(beanFactory); try { // ⑤空方法,留由子类实现。
//例如注册servlet相关的忽略接口、beanPostProcessor、各作用域生成bean的bean工厂
//注册servlet的一些单例(servletContext/servletConfig/contextparameters/contextAttributes)到beanfactory的单例容器中 postProcessBeanFactory(beanFactory); // ⑥beanFactoryPostProcessor排序并依次调用
// beanFactoryPostProcessor:beanfactory的后置处理器,可以理解为一个beanfactory的拦截器(实例化后需要执行的自定义操作)
// 例如:beanfactory初始化完成后,修改忽略接口、甚至可以对特定的beandefinition做修改 invokeBeanFactoryPostProcessors(beanFactory); // ⑦BeanPostProcessors排序并依次注册到beanfactory的beanpostProcessor容器中
// beanPostProcessors:bean实例化的处理器,可以理解为一个bean的拦截器(实例化前+实例化后需要执行自定义操作)
// 例如:bean单例化前,修改beandefinition的属性。
//实例化后DI,
//拦截getbean()拦截返回一个代理类bean registerBeanPostProcessors(beanFactory); // ⑧初始化国际化文件,支持国际化 initMessageSource(); // ⑨初始化时间监听器并注册到beanfactory的单例容器中 initApplicationEventMulticaster(); // ⑩空方法,子类实现,初始化一些自定义bean并注册到beanfactory的单例容器中
// 例如:themeSource,支持主题切换 onRefresh(); // ⑪注册个中监听器到beanfactory指定容器中 registerListeners(); // ⑫实例化不需要延迟加载的所有单例类型的bean(scope = singleton) finishBeanFactoryInitialization(beanFactory); // ⑬容器初始化完成,触发各种事件监控,ApplicationListener.onApplicationEvent()的执行时机(dubbo注册就是在这里实现的)
// 例如:beanfactory的生命周期监控 finishRefresh(); } catch (BeansException ex) { if (logger.isWarnEnabled()) { logger.warn("Exception encountered during context initialization - " + "cancelling refresh attempt: " + ex); } // ⑭ 容器初始化失败,销毁所有已实例化的bean destroyBeans(); // ⑮ 设置active = false cancelRefresh(ex); // Propagate exception to caller. throw ex; } finally { // ⑯ 清空公共的反射缓存 resetCommonCaches(); } } }
① 加锁:也是SpringIOC中主要加锁方式
private final Object startupShutdownMonitor = new Object(); @Override public void refresh() throws BeansException, IllegalStateException { synchronized (this.startupShutdownMonitor) { ... } }
利用synchronized实现的一个细粒度锁。拥有ReentranLock.lock()的细粒度,还不用释放unlock()。
② prepareRefresh():IOC容器初始化之前的准备(配置环境参数,创建监听器容器,创建事件容器)
protected void prepareRefresh() { // 容器开始时间+容器关闭开启状态 this.startupDate = System.currentTimeMillis(); this.closed.set(false); this.active.set(true); if (logger.isDebugEnabled()) { if (logger.isTraceEnabled()) { logger.trace("Refreshing " + this); } else { logger.debug("Refreshing " + getDisplayName()); } } //初始化IOC容器的一些环境参数,默认空方法,子类可重写 //这里可以先创建一个标准环境变量StandardEnvironment,然后设置一些环境参数 //并且指定一些必须配置的参数 initPropertySources(); //若未创建,则创建一个标准环境变量StandardEnvironment //校验上面指定的必须配置的参数是否已经配置,没有配置会抛出异常 getEnvironment().validateRequiredProperties(); // 配置一些refresh()之前的监听器 if (this.earlyApplicationListeners == null) { this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners); } else { // Reset local application listeners to pre-refresh state. this.applicationListeners.clear(); this.applicationListeners.addAll(this.earlyApplicationListeners); } //创建是一个事件集合 this.earlyApplicationEvents = new LinkedHashSet<>(); }
③ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory():控制refresh调用次数。
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() { //抽象方法,控制IOC容器的refresh()次数 //仅允许refresh()一次,再次刷新会报错:GenericApplicationContext.java //允许重复刷新():AbstractRefreshableApplicationContext.java ,
//刷新逻辑是销毁旧beanfactory,实例化一个新的beanfactory;当然没有旧beanfactory这里会直接实例化一个beanfactory
//并且重新扫描生成beanDefinitionMap容器 refreshBeanFactory(); //抽象方法 //返回容器类ApplicationContext创建时创建的DefaultListableBeanFactory实例 return getBeanFactory(); } /* org/springframework/context/support/AbstractRefreshableApplicationContext.java:129 */ protected final void refreshBeanFactory() throws BeansException { if (hasBeanFactory()) { //允许重复刷新,销毁旧beanfactory destroyBeans(); closeBeanFactory(); } try { //创建新的beanfactory //传统的基于xml解析的ApplicationContext,例如spring2.x经常拿来学习的ClassPathXmlApplitionContext.java //beanfactory是在这里实例化的,而不是在applicationContext的构造方法中 DefaultListableBeanFactory beanFactory = createBeanFactory(); beanFactory.setSerializationId(getId()); customizeBeanFactory(beanFactory); //重新扫描生成beandefinitionMap容器 loadBeanDefinitions(beanFactory); synchronized (this.beanFactoryMonitor) { this.beanFactory = beanFactory; } } catch (IOException ex) { throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex); } }
④prepareBeanFactory(beanFactory):设置DefaultListableBeanFactory实例的属性(类加载器,忽略接口,BeanPostProcessor,将环境变量单例注册到beanfactory中)
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) { // Tell the internal bean factory to use the context's class loader etc. //设置类加载器 beanFactory.setBeanClassLoader(getClassLoader()); beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment())); // Configure the bean factory with context callbacks. //设置BeanPostProcessor(后置处理器) beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); //设置需要忽略的接口,这些接口的实现类不会被IOC容器实例化 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接口不能注册为一个简单工厂的解析类型 //自动转配bean 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. //设置BeanPostProcessor后置处理器 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); // Detect a LoadTimeWeaver and prepare for weaving, if found. if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); // Set a temporary ClassLoader for type matching. beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } //将环境单例StandardEnvironment注册到beanfactory单例容器中 if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment()); } if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties()); } if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) { beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment()); } }
⑤postProcessBeanFactory(beanFactory):抽象方法,子类具体实现
选取AnnotationConfigApplication的父类GenericWebApplicationContext:
将serlvet相关的后置处理器、作用域类型、servlet的bean的创建工厂设置到beanfactory中
将serlvet的servletContext、servletConfig、contextParameters、contexAttributes注册到beanfactory的单例容器中
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { if (this.servletContext != null) { //注册servletContext相关处理器 //忽略servletContext相关的接口 beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext)); beanFactory.ignoreDependencyInterface(ServletContextAware.class); } //注册beanfactory的servlet的三个作用域实例,并指定servlet相关类型的bean的创建工厂 WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext); //servletContex、servletConfig、contextParameters、contextAttributes实例注册到beanfactory的单例容器中 WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext); } /* WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext); */ public static void registerWebApplicationScopes(ConfigurableListableBeanFactory beanFactory, @Nullable ServletContext sc) { //注册servlet作用域 request session //request:一个请求创建一个request //session:一次会话创建一个session beanFactory.registerScope(WebApplicationContext.SCOPE_REQUEST, new RequestScope()); beanFactory.registerScope(WebApplicationContext.SCOPE_SESSION, new SessionScope()); if (sc != null) { //注册servlet作用域 application //application:所有用户共享 ServletContextScope appScope = new ServletContextScope(sc); beanFactory.registerScope(WebApplicationContext.SCOPE_APPLICATION, appScope); // Register as ServletContext attribute, for ContextCleanupListener to detect it. sc.setAttribute(ServletContextScope.class.getName(), appScope); } //注册对应类型的实例工厂 beanFactory.registerResolvableDependency(ServletRequest.class, new RequestObjectFactory()); beanFactory.registerResolvableDependency(ServletResponse.class, new ResponseObjectFactory()); beanFactory.registerResolvableDependency(HttpSession.class, new SessionObjectFactory()); beanFactory.registerResolvableDependency(WebRequest.class, new WebRequestObjectFactory()); if (jsfPresent) { FacesDependencyRegistrar.registerFacesDependencies(beanFactory); } } /* WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext); */ public static void registerEnvironmentBeans(ConfigurableListableBeanFactory bf, @Nullable ServletContext servletContext, @Nullable ServletConfig servletConfig) { //将servletContext实例注册到beanfactory单例容器中 if (servletContext != null && !bf.containsBean(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME)) { bf.registerSingleton(WebApplicationContext.SERVLET_CONTEXT_BEAN_NAME, servletContext); } //将servletConfig实例注册到beanfactory单例容器中 if (servletConfig != null && !bf.containsBean(ConfigurableWebApplicationContext.SERVLET_CONFIG_BEAN_NAME)) { bf.registerSingleton(ConfigurableWebApplicationContext.SERVLET_CONFIG_BEAN_NAME, servletConfig); } //将contextParameters转化成一个Map注册到beanfactory的单例容器中 if (!bf.containsBean(WebApplicationContext.CONTEXT_PARAMETERS_BEAN_NAME)) { Map<String, String> parameterMap = new HashMap<>(); if (servletContext != null) { Enumeration<?> paramNameEnum = servletContext.getInitParameterNames(); while (paramNameEnum.hasMoreElements()) { String paramName = (String) paramNameEnum.nextElement(); parameterMap.put(paramName, servletContext.getInitParameter(paramName)); } } if (servletConfig != null) { Enumeration<?> paramNameEnum = servletConfig.getInitParameterNames(); while (paramNameEnum.hasMoreElements()) { String paramName = (String) paramNameEnum.nextElement(); parameterMap.put(paramName, servletConfig.getInitParameter(paramName)); } } bf.registerSingleton(WebApplicationContext.CONTEXT_PARAMETERS_BEAN_NAME, Collections.unmodifiableMap(parameterMap)); } //将contextAttributes转化成Map注册到beanfactory的单例容器中 if (!bf.containsBean(WebApplicationContext.CONTEXT_ATTRIBUTES_BEAN_NAME)) { Map<String, Object> attributeMap = new HashMap<>(); if (servletContext != null) { Enumeration<?> attrNameEnum = servletContext.getAttributeNames(); while (attrNameEnum.hasMoreElements()) { String attrName = (String) attrNameEnum.nextElement(); attributeMap.put(attrName, servletContext.getAttribute(attrName)); } } bf.registerSingleton(WebApplicationContext.CONTEXT_ATTRIBUTES_BEAN_NAME, Collections.unmodifiableMap(attributeMap)); } }
⑥ invokeBeanFactoryPostProcessors(beanFactory):需要与上面的BeanPostProcessors区分开,主要是区分两类PostProcessor,然后对bean相关的postjProcessor实例按照优先级排序,按照优先级顺序调用。
BeanPostProcessors:处理特定的bean的后置处理器,(bean实例化的拦截器)
BeanFactoryPostProcessors:处理beanfactory下所有bean的后置处理器
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) { //这个方法很长有点复杂 //1、具体beanfactory中后置处理器beanFactoryPostProcessor分为两类 //①bean注册相关的后置处理器:BeanDefinitionRegistryPostProcessors //②普通后置处理器 //2、将上面①中后置处理器按照优先级逐一调用 //①实现PriorityOrdered接口的 //②实现Ordered接口的 //③其他BeanDefinitionRegistryPostProcessors PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors()); // Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor) //目前还不清楚loadTimeWeaver的作用 if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) { beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory)); beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader())); } }
⑦ registerBeanPostProcessors(beanFactory):其实内容跟上面⑥差不多,只是处理对象不同了。beanPostProcessor实例按照优先级顺序注册到beanfactory的beanpostprocessor容器中。
a 实现PriorityOrdered接口的
b 实现Ordered接口的,未实现MergedBeanDefinitionPostProcessor接口的
c 剩下的未实现MergedBeanDefinitionPostProcessor接口的
d 实现MergedBeanDefinitionPostProcessor接口的
e 提供一个末位动态注册器,可从bean单例中拉取监听器到末尾
public static void registerBeanPostProcessors( ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) { 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. //获取所有beanProcessor,并注册一个记录beanProcessor数量的BeanPostProcessor int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length; beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount)); // 将beanPostProcessor区分为四类类然后按此顺序注册到beanfactory中 // 实现PriorityOrdered接口的 // 实现Ordered接口的,未实现MergedBeanDefinitionPostProcessor接口的 // 剩下的未实现MergedBeanDefinitionPostProcessor接口的 // 实现MergedBeanDefinitionPostProcessor接口的 List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>(); List<BeanPostProcessor> internalPostProcessors = new ArrayList<>(); List<String> orderedPostProcessorNames = new ArrayList<>(); List<String> nonOrderedPostProcessorNames = new ArrayList<>(); for (String ppName : postProcessorNames) { if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); priorityOrderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } else if (beanFactory.isTypeMatch(ppName, Ordered.class)) { orderedPostProcessorNames.add(ppName); } else { nonOrderedPostProcessorNames.add(ppName); } } // First, register the BeanPostProcessors that implement PriorityOrdered. //将实现PriorityOrdered接口的先排序,后注册 sortPostProcessors(priorityOrderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors); // Next, register the BeanPostProcessors that implement Ordered. //将实现Ordered接口的,排序注册 List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size()); for (String ppName : orderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); orderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } sortPostProcessors(orderedPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, orderedPostProcessors); // Now, register all regular BeanPostProcessors. //将剩余的,后注册 List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size()); for (String ppName : nonOrderedPostProcessorNames) { BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class); nonOrderedPostProcessors.add(pp); if (pp instanceof MergedBeanDefinitionPostProcessor) { internalPostProcessors.add(pp); } } registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors); // Finally, re-register all internal BeanPostProcessors. //将实现MergedBeanDefinitionPostProcessor接口重新注册(原来注册过的会删除后,再注册,所以优先级比上面三种低) sortPostProcessors(internalPostProcessors, beanFactory); registerBeanPostProcessors(beanFactory, internalPostProcessors); // 注册一个末尾的处理器,可以实现,动态将bean单例中的applicationContextListener注册到末尾(优先级最低) beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext)); }
⑧ initMessageSource():国际化支持,注册一个new DelegatingMessageSource()到beanfactory的单例容器中,支持继承关系
protected void initMessageSource() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); //国际化支持,支持继承关系 if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) { this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class); // Make MessageSource aware of parent MessageSource. if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) { HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource; if (hms.getParentMessageSource() == null) { // Only set parent context as parent MessageSource if no parent MessageSource // registered already. hms.setParentMessageSource(getInternalParentMessageSource()); } } if (logger.isTraceEnabled()) { logger.trace("Using MessageSource [" + this.messageSource + "]"); } } else { // Use empty MessageSource to be able to accept getMessage calls. DelegatingMessageSource dms = new DelegatingMessageSource(); dms.setParentMessageSource(getInternalParentMessageSource()); this.messageSource = dms; beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource); if (logger.isTraceEnabled()) { logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]"); } } }
⑨ initApplicationEventMulticaster():注册一个applicationEvent多路广播器到beanfactory的单例容器中
protected void initApplicationEventMulticaster() { ConfigurableListableBeanFactory beanFactory = getBeanFactory(); // 初始化一个applicationEvent多路广播,具体作用未知 if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) { this.applicationEventMulticaster = beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class); if (logger.isTraceEnabled()) { logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]"); } } else { this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory); beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster); if (logger.isTraceEnabled()) { logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " + "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]"); } } }
⑩ onrefresh():空方法,初始化一些特殊的bean。
AnnotationConfigApplicationContext:创建themeSource,主题资源注册
protected void onRefresh() { this.themeSource = UiApplicationContextUtils.initThemeSource(this); } public static ThemeSource initThemeSource(ApplicationContext context) { if (context.containsLocalBean(THEME_SOURCE_BEAN_NAME)) { ThemeSource themeSource = context.getBean(THEME_SOURCE_BEAN_NAME, ThemeSource.class); // Make ThemeSource aware of parent ThemeSource. if (context.getParent() instanceof ThemeSource && themeSource instanceof HierarchicalThemeSource) { HierarchicalThemeSource hts = (HierarchicalThemeSource) themeSource; if (hts.getParentThemeSource() == null) { // Only set parent context as parent ThemeSource if no parent ThemeSource // registered already. hts.setParentThemeSource((ThemeSource) context.getParent()); } } if (logger.isDebugEnabled()) { logger.debug("Using ThemeSource [" + themeSource + "]"); } return themeSource; } else { // Use default ThemeSource to be able to accept getTheme calls, either // delegating to parent context's default or to local ResourceBundleThemeSource. HierarchicalThemeSource themeSource = null; if (context.getParent() instanceof ThemeSource) { themeSource = new DelegatingThemeSource(); themeSource.setParentThemeSource((ThemeSource) context.getParent()); } else { themeSource = new ResourceBundleThemeSource(); } if (logger.isDebugEnabled()) { logger.debug("Unable to locate ThemeSource with name '" + THEME_SOURCE_BEAN_NAME + "': using default [" + themeSource + "]"); } return themeSource; } }
⑪registerListeners():将各种监听器放入到对应的容器中
protected void registerListeners() { // Register statically specified listeners first. 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! String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false); for (String listenerBeanName : listenerBeanNames) { getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName); } // Publish early application events now that we finally have a multicaster... Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents; this.earlyApplicationEvents = null; if (earlyEventsToProcess != null) { for (ApplicationEvent earlyEvent : earlyEventsToProcess) { getApplicationEventMulticaster().multicastEvent(earlyEvent); } } }
⑫finishBeanFactoryInitialization(beanFactory):bean实例化,单独开一章研究
⑬finishRefresh();refresh结束,推送相关事件
protected void finishRefresh() { //清空资源缓存 clearResourceCaches(); // 初始化容器的生命周期处理器 initLifecycleProcessor(); // 将refresh推送给生命周期处理器 getLifecycleProcessor().onRefresh(); // 监听器执行,ApplicationListener.onApplicationEvent() publishEvent(new ContextRefreshedEvent(this)); // 注册容器到LiveBeansView中,由LiveBeansView监控容器? LiveBeansView.registerApplicationContext(this); }
⑭destroyBeans():refresh失败时,删除已经创建的单例bean
⑮cancelRefresh(ex);refresh失败时,设置active标志=false
⑯resetCommonCaches();清空公共反射缓存
protected void resetCommonCaches() { ReflectionUtils.clearCache(); AnnotationUtils.clearCache(); ResolvableType.clearCache(); CachedIntrospectionResults.clearClassLoader(getClassLoader()); }