写一个类实现ApplicationListener<ContextRefreshedEvent>接口
@Service
public class Xzh implements ApplicationListener<ContextRefreshedEvent> {
}
并实现方法onApplicationEvent()方法
onApplicationEvent 是一个事件响应方法,该方法会在收到 Spring 上下文刷新事件后执行
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
System.out.println("xzh");
}
启动spring后,会打印xzh
另外还有其他事件ContextClosedEvent 、ContextRefreshedEvent 、ContextStartedEvent 、ContextStoppedEvent 、RequestHandleEvent
(1)上下文更新事件(ContextRefreshedEvent):在调用ConfigurableApplicationContext 接口中的refresh()方法时被触发。
(2)上下文开始事件(ContextStartedEvent):当容器调用ConfigurableApplicationContext的Start()方法开始/重新开始容器时触发该事件。
(3)上下文停止事件(ContextStoppedEvent):当容器调用ConfigurableApplicationContext的Stop()方法停止容器时触发该事件。
(4)上下文关闭事件(ContextClosedEvent):当ApplicationContext被关闭时触发该事件。容器被关闭时,其管理的所有单例Bean都被销毁。
(5)请求处理事件(RequestHandledEvent):在Web应用中,当一个http请求(request)结束触发该事件。