实现方法
方法一:实现ApplicationListener< ContextRefreshedEvent>接口
实现ApplicationListener接口,并实现 onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent)方法
1 @Service 2 public class SearchReceive implements ApplicationListener<ContextRefreshedEvent> { 3 @Override 4 public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { 5 if (contextRefreshedEvent.getApplicationContext().getParent() == null) {//保证只执行一次 6 //需要执行的方法 7 } 8 } 9 } 10
方法二:SpringBoot的ApplicationRunner
1 @Component 2 public class JDDRunner implements ApplicationRunner { 3 @Override 4 public void run(ApplicationArguments args) throws Exception { 5 System.out.println(args); 6 System.out.println("这个是测试ApplicationRunner接口"); 7 } 8 } 9