Spring通过ApplicationListener接口来触发contextrefreshedevent事件
在开发时有时候需要在整个应用开始运行时执行一些特定代码,比如初始化环境,准备测试数据、加载一些数据到内存等等。
在Spring中可以通过ApplicationListener来实现相关的功能,加载完成后触发contextrefreshedevent事件(上下文件刷新事件)
基类
public abstract class AbsBasicListener<T extends ApplicationEvent> implements
ApplicationListener<T> {
protected Logger LOG = LoggerFactory.getLogger(getClass());
}
实现类
@Component
public class FsTokenScheduleServer extends AbsBasicListener<ContextRefreshedEvent> {
@Autowired
protected ApplicationContext context;
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
//开关
if (!Dict.getBoolean("sys.fsTokenSchedule", false))
return;
//防止重复执行
if (event.getApplicationContext().getParent() == null) {
new Thread(new FsAccessTokenTimer(context)).start();
}
}
}