[spring] source code-finishRefresh() method of spring container startup process (11)

Table of contents

finishRefresh()

   initLifecycleProcessor()

  onRefresh()

contextDestroyed()


 

finishRefresh()

      protected void finishRefresh() {
		// Clear context-level resource caches (such as ASM metadata from scanning).
		clearResourceCaches();

		// Initialize lifecycle processor for this context.
		// 为应用上下文 初始化 LifecycleProcessor
		initLifecycleProcessor();

		// Propagate refresh to lifecycle processor first.
		getLifecycleProcessor().onRefresh();

		// Publish the final event.
		//推送上下文刷新完毕事件到相应的监听器
		publishEvent(new ContextRefreshedEvent(this));

		// Participate in LiveBeansView MBean, if active.
		LiveBeansView.registerApplicationContext(this);
	}

   initLifecycleProcessor()

protected void initLifecycleProcessor() {
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		//判断BeanFactory是否已经存在生命周期处理器(固定使用beanName=lifecycleProcessor
		if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
			this.lifecycleProcessor =
					beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
			if (logger.isDebugEnabled()) {
				logger.debug("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
			}
		}
		else {
			// 不存在就使用默认DefaultLifecycleProcessor
			DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
			defaultProcessor.setBeanFactory(beanFactory);
			this.lifecycleProcessor = defaultProcessor;
			// 把默认处理器注册到容器种
			beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
			if (logger.isDebugEnabled()) {
				logger.debug("Unable to locate LifecycleProcessor with name '" +
						LIFECYCLE_PROCESSOR_BEAN_NAME +
						"': using default [" + this.lifecycleProcessor + "]");
			}
		}
	}

  onRefresh()

    @Override
	public void onRefresh() {
		startBeans(true);
		this.running = true;
	}



	  private void startBeans(boolean autoStartupOnly) {
		// 返回所有实现了Lifecycle bean
		Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
		//key:如果实现了SmartLifeCycle,则为其getPhase方法返回的值,如果只是实现了Lifecycle,默认返回0
		 // value:相同phase的Lifecycle的集合,并将其封装到了一个LifecycleGroup中
		Map<Integer, LifecycleGroup> phases = new HashMap<>();
		lifecycleBeans.forEach((beanName, bean) -> {
			if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
				// 获得当前bean 的优先级
				int phase = getPhase(bean);
				//分组
				LifecycleGroup group = phases.get(phase);
				if (group == null) {
					group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly);
					phases.put(phase, group);
				}
				group.add(beanName, bean);
			}
		});
		if (!phases.isEmpty()) {
			List<Integer> keys = new ArrayList<>(phases.keySet());
			//排序
			Collections.sort(keys);
			for (Integer key : keys) {
				phases.get(key).start();
			}
		}
	}

Parsing: group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly) Parameter explanation:

                phase: represents the execution phase of this group of lifecycleBeans;
                timeoutPerShutdownPhase: Because the stop method in lifecycleBean can run in another thread, in order to ensure that all lifecycleBean in the current phase are executed, Spring uses CountDownLatch to prevent timeout waiting, all A maximum waiting time is set here, and the default is 30 seconds;
                lifecycleBeans: all Beans that implement Lifecycle;
                autoStartupOnly: false when the start method of the container is called manually. true when the container startup phase is called automatically;

Lifecycle interface : Any object managed by Spring can implement this interface. When the ApplicationContext interface is started and closed, it will call all Lifecycle implementations in this container

The implementation classes are LifecycleProcessor and LifecycleProcessor;

LifecycleProcessor: Two extension methods are added. The default implementation of the LifecycleProcessor interface in Spring is the DefaultLifecycleProcessor class, which waits for a timeout for each callback. The default timeout is 30 seconds. The default parameters of this class can be overridden, and the default bean name of this class in the container is lifecycleProcessor. Such as modifying the timeout

SmartLifecycle: Inherited from the Phased class, the stop() method in SmartLifecycle has a callback parameter. All implementations will call the run() method of the callback after the shutdown process is completed, which is equivalent to enabling the asynchronous shutdown function.

 

contextDestroyed()

It will be triggered when we stop the container to release resources;

/**
	 * 销毁根web应用程序上下文.
	 */
	@Override
	public void contextDestroyed(ServletContextEvent event) {
		closeWebApplicationContext(event.getServletContext());
		ContextCleanupListener.cleanupAttributes(event.getServletContext());
	}
closeWebApplicationContext(ServletContext servletContext) 方法用来将上下文置为空 ,同时把根容器也从上下文中移除;
public void closeWebApplicationContext(ServletContext servletContext) {
		servletContext.log("Closing Spring root WebApplicationContext");
		try {
			if (this.context instanceof ConfigurableWebApplicationContext) {
				((ConfigurableWebApplicationContext) this.context).close();
			}
		}
		finally {
			ClassLoader ccl = Thread.currentThread().getContextClassLoader();
			if (ccl == ContextLoader.class.getClassLoader()) {
				// 置空
				currentContext = null;
			}
			else if (ccl != null) {
				currentContextPerThread.remove(ccl);
			}
			// 移除根容器
			servletContext.removeAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE);
		}
	}东方鲤鱼

 

Guess you like

Origin blog.csdn.net/zy_jun/article/details/115347204