spring常用事件

spring中已经内置的几种事件: ContextClosedEvent   、ContextRefreshedEvent  、ContextStartedEvent  、ContextStoppedEvent   、RequestHandleEvent 

本次主要讲解ContextRefreshedEvent事件

 ---->该事件会在ApplicationContext被初始化会触发

使用场景:比如初始化线程多个线程或者做一些启动后的事情

实战内容

@Component

public class InitQueue implements ApplicationListener<ContextRefreshedEvent> {

     @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {

        if (event.getApplicationContext().getParent() != null) {

          //必须加上该判断,否则会系统初始化两次 

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

       }

    }

猜你喜欢

转载自blog.csdn.net/qq_39291929/article/details/80313452