public class StartApplicationListener implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext(); ApplicationContext parent = applicationContext.getParent(); if (parent == null) { CacheManager cacheManager = applicationContext.getBean(CacheManager.class); Cache cache = cacheManager.getCache(MsConstants.NODE_CACHE_NAME); new Thread(new Runnable() { @Override public void run() { //代码 } }).start(); } }
public static void main(String[] args) { SpringApplication app = new SpringApplication(FigureServerApplication.class); app.addListeners(new StartApplicationListener()); app.run(args); }
本文介绍了一个SpringBoot应用中实现的启动监听器示例。该监听器会在Spring上下文刷新后执行特定任务,例如初始化缓存。通过覆写`onApplicationEvent`方法并在`main`方法中注册监听器来实现。
951





