Spring项目启动自动执行一次指定方法

Spring项目启动自动执行一次指定方法

   点关注不迷路,欢迎再访!		

实现ApplicationListener接口,并实现 onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent)方法

springmvc:

@Service
public class SearchReceive implements  ApplicationListener<ContextRefreshedEvent> {
    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        if (contextRefreshedEvent.getApplicationContext().getParent() == null) {//保证只执行一次
            //需要执行的方法
        }
    }
}

为什么先做判断?

Spring存在两个容器:一个是root application context ,另一个就是我们自己的 projectName-servlet context(作为root application context的子容器)。这种情况下,就会造成onApplicationEvent方法被执行两次。为了避免上面提到的问题,我们可以只在root application context初始化完成后调用逻辑代码,其他的容器的初始化完成,则不做任何处理。

发布了101 篇原创文章 · 获赞 33 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_39443053/article/details/103448264