springboot项目启动后执行方法,有三种实现方式。
1 方法
- ApplicationListener< ContextRefreshedEvent> 不推荐
- ApplicationListener 推荐
- CommandLineRunner 推荐
方法1:spring的ApplicationListener< ContextRefreshedEvent>接口
实现ApplicationListener接口,并实现 onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent)方法
@Service
public class SearchReceive implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
if (contextRefreshedEvent.getApplicationContext().getParent() == null) {//保证只执行一次
//需要执行的方法
}
}
}
方法2:springboot的ApplicationRunner接口
ApplicationListener和CommandLineRunner两个接口是springBoot提供用来在spring容器加载完成后执行指定方法。两个接口区别主要是入参不同。<