web服务启动spring自己主动运行ApplicationListener的使用方法

我们知道。一般来说一个项目启动时须要载入或者运行一些特殊的任务来初始化系统。通常的做法就是用servlet去初始化。可是servlet在使用spring bean时不能直接注入,还须要在web.xml配置。比較麻烦。今天介绍一下使用spring启动初始化的方法。事实上非常easy,仅仅需两步就能够了。

  1. 实现ApplicationListener接口:
public class Init implements ApplicationListener<ContextRefreshedEvent>{

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

        if(event.getApplicationContext().getParent() == null){//root application context 没有parent
            //TODO 这里写下将要初始化的内容

        }
    }

}
  1. 在spring applicationContex.xml中配置该bean
 <bean class="com.xx.xxx.Init"/>

这样服务启动时。就会自己主动载入并运行了。

原文地址:https://www.cnblogs.com/gavanwanggw/p/7071025.html