目录
一、介绍说明
1、ApplicationListener介绍
ApplicationListener是Spring 框架中的监听和处理应用事件。
2、ApplicationListener的工作原理
ApplicationListener的工作原理基于发布-订阅模式。事件发布者(ApplicationEventPublisher)发布事件,而事件监听器(实现了ApplicationListener接口的类)则监听这些事件。当事件发生时,所有注册了该事件的监听器都会被调用,执行相应的操作。从而实现了系统的解耦和可扩展性。
3、ContextRefreshedEvent介绍
ContextRefreshedEvent事件是一个重要的事件。
A:在spring 应用上下文初始化完成后触发。
B:在spring应用上下文被刷新时:例如调用refresh()方法。
二、示例
import com.test.task.TaskManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;
@Slf4j
@Component
public class ApplicationContextListener implements ApplicationListener<ContextRefreshedEvent>{
@Autowired
private TaskManager taskManager;
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
try {
//调用初始化方法
taskManager.init();
log.info("初始化消息信息加载完毕--------------------");
}catch (Exception e){
log.error("启动服务出现异常,e=",e);
//关闭程序
System.exit(1);
}
}
}
注意事项:
1、实现ApplicationListener<ContextRefreshedEvent>接口重写onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent)方法。
2、onApplicationEvent方法中调用需要初始化的方法,并处理异常,异常时,关闭程式。