zoukankan      html  css  js  c++  java
  • web服务启动spring自动执行ApplicationListener的用法

    我们知道,一般来说一个项目启动时需要加载或者执行一些特殊的任务来初始化系统,通常的做法就是用servlet去初始化,但是servlet在使用spring bean时不能直接注入,还需要在web.xml配置,比较麻烦。今天介绍一下使用spring启动初始化的方法。其实很简单,只需两步就可以了。

    在开发时有时候需要在整个应用开始运行时执行一些特定代码,比如初始化环境,准备测试数据、加载一些数据到内存等等。

    spring中可以通过ApplicationListener来实现相关的功能,加载完成后触发contextrefreshedevent事件(上下文件刷新事件)

    但是这个时候,会存在一个问题,在web 项目中(spring mvc),系统会存在两个容器,一个是root application context ,另一个就是我们自己的 projectName-servlet  context(作为root application context的子容器)。

    这种情况下,就会造成onApplicationEvent方法被执行两次。为了避免上面提到的问题,我们可以只在root application context初始化完成后调用逻辑代码,其他的容器的初始化完成,则不做任何处理,修改后代码

    1. 实现ApplicationListener接口:
    public class Init implements ApplicationListener<ContextRefreshedEvent>{
    
        @Override
        public void onApplicationEvent(ContextRefreshedEvent event) {
    
            if(event.getApplicationContext().getParent() == null){//root application context 没有parent
                //TODO 这里写下将要初始化的内容
    
            }
        }
    
    }

             2. 在spring applicationContex.xml中配置该bean

     <bean id="cmsApplicationListener" class="com.xx.xxx.Init"/>

    这样服务启动时,就会自动加载并执行了。

    后续发现加上以上判断还是能执行两次,不加的话三次,最终研究结果使用以下判断更加准确:event.getApplicationContext().getDisplayName().equals("Root WebApplicationContext")

  • 相关阅读:
    表格转换,多行聚集成列,长列转换成多行
    记第一次写数据库文章总结
    免疫 TCR BCR 病毒滴度
    Genome-wide Study Identifies Association between HLA-B*55:01 and Self-Reported Penicillin Allergy
    LD plot
    beta p-value SE
    蛋白截断变异(protein-truncating variant,PTV)
    The human noncoding genome defined by genetic diversity
    Fst计算
    LD Score regression文章 ;confounding
  • 原文地址:https://www.cnblogs.com/xxj-bigshow/p/7244822.html
Copyright © 2011-2022 走看看