spring容器初始化结束发布的事件
spring在容器结束时,会发布一个 ContextRefreshedEvent 事件,用户只需要写一个事件监听器,监听这个事件,就能实现在spring初始化结束之后做一些事情
package com.example.myspringdemo.springextend;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class ListenerDemo implements ApplicationListener {
@Override
public void onApplicationEvent(ApplicationEvent event) {
log.info("spring发布的事件:{}" , event.getClass());
if(event instanceof ContextRefreshedEvent){
log.info("系统启动成功:{}" , event.getClass());
}
}
}
springBoot
Spring Boot 提供了 ApplicationRunner 和 CommandLineRunner 用于完成启动后的初始化工作,我们只要实现继承这个接口并实现其中的 run 方法就可以了。
等看到了springboot源码之后,再进行补充