千家信息网

如何使用prepareRefresh()

发表于:2025-11-16 作者:千家信息网编辑
千家信息网最后更新 2025年11月16日,这篇文章主要介绍"如何使用prepareRefresh()",在日常操作中,相信很多人在如何使用prepareRefresh()问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家
千家信息网最后更新 2025年11月16日如何使用prepareRefresh()

这篇文章主要介绍"如何使用prepareRefresh()",在日常操作中,相信很多人在如何使用prepareRefresh()问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"如何使用prepareRefresh()"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

refresh()

这个方法主要做了一下这几件事情:

  • 容器刷新前的准备

  • 初始化beanFactory,加载并解析配置

  • 设置beanFactory的属性

  • BeanFactory创建完成后进行的后置处理工作

  • 执行BeanFactoryPostProcessor的方法

  • 注册BeanPostProcessor

  • 初始化MessageSource组件

  • 初始化事件派发器

  • 子类重写这个方法,在容器刷新的时候可以自定义逻辑

  • 给容器中将所有项目里面的ApplicationListener注册进来

  • 初始化所有剩下的单实例bean

  • 完成BeanFactory的初始化创建工作,IOC容器就创建完成

这里我们先来看看容器刷新前做了些什么吧

prepareRefresh()

方法的源码并不多,如下:

protected void prepareRefresh() {        // Switch to active.        // 这一句很明显的获取了系统当前时间,其实他的作用是来记录当前的启动时间的        this.startupDate = System.currentTimeMillis();                // 这两个状态的设置,前者关闭程序设置为false,后者运行标识设置为true        this.closed.set(false);        this.active.set(true);        if (logger.isDebugEnabled()) {                if (logger.isTraceEnabled()) {                        logger.trace("Refreshing " + this);                }                else {                        logger.debug("Refreshing " + getDisplayName());                }        }        // Initialize any placeholder property sources in the context environment.        // 目前还是一个空方法,应该后面会补充        initPropertySources();        // Validate that all properties marked as required are resolvable:        // see ConfigurablePropertyResolver#setRequiredProperties        // 校验 xml配置文件        getEnvironment().validateRequiredProperties();        // Store pre-refresh ApplicationListeners...        // 判断刷新前的运用程序监听集合是否为空,为空初始化applicationListeners监听,不为空,则清空监听器        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);        }        // Allow for the collection of early ApplicationEvents,        // to be published once the multicaster is available...        // 创建刷新前的事件集合        this.earlyApplicationEvents = new LinkedHashSet<>();}

这个方法prepareRefresh(),是在spring5.3之后加了程序,所以之前的版本是没有办法看到的。

就做了这几件事情

  • 设置容器的启动时间

  • 设置活跃状态为true

  • 设置关闭状态为false

  • 获取Environment对象,并加载当前系统的环境到Environment中

  • 准备监听器和事件的集合对象,默认为空

到此,关于"如何使用prepareRefresh()"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!

0