第一种:
实现接口ApplicationListener,并重写public void onApplicationEvent(ApplicationEvent event) {}可以在容器初始话的时候执行这个方法。
事件类型有以下几种:
1、ApplicationContextEvent
是spring内置事件的父抽象类,构造方法传入spring的context容器,同时也有获取spring的context容器的方法。
2、ContextRefreshedEvent
当spring容器初始化或刷新时,会触发此事件。此事件在开发中常用,用于在spring容器启动时,导入自定义的bean实例到spring容器中。
3、ContextStartedEvent
当spring启动时,或者说是context调用start()方法时,会触发此事件。
4、ContextStoppedEvent
当spring停止时,或者说context调用stop()方法时,会触发此事件。
5、ContextClosedEvent
当spring关闭时,或者说context调用close()方法时,会触发此事件。
package com.sinosoft.speech.util;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
/**
* spring boot 容器加载完成后执行
*/
public class ApplicationStartup implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
// 初始化完成后. 执行一次同步系统参数
Scheduler scheduler = contextRefreshedEvent.getApplicationContext().getBean(Scheduler.class);
scheduler.syncSysParam();
}
}
可以在ApplicationStartup中添加类注解@Component,让spring容器管理起来。
或者在springboot启动类中手动添加listeners
public static void main(String[] args) {
SpringApplication app = new SpringApplication(App.class);
app.addListeners(new ApplicationStartup());
app.run(args);
}
第二种
spring容器加载完自动监听
实现springboot默认的监听接口即可,该方法在spring容器加载完自动监听
package com.sinosoft.speech.util;
import com.sinosoft.speech.swing.Main;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
/**
* spring boot 容器加载后自动监听
*/
@Component
public class MyCommandRunner implements CommandLineRunner {
@Override
public void run(String... args) {System.setProperty("address", JsonUtils.objectToJson(addressList));
//System.out.println("开始启动1个页面");
//try {
// Runtime.getRuntime().exec("cmd /c start http://localhost:8080/index");
//} catch (Exception ex) {
// ex.printStackTrace();
//}
}
}