应用程序启动后首先被调用CommandLineRunner

public void run(String... args),最重要的是:这个方法会在应用程序启动后首先被调用
那种只需要在应用程序启动时执行一次的任务,非常适合利用Command line runners来完成。
Spring Boot应用程序在启动后,会遍历CommandLineRunner接口的实例并运行它们的run方法。
也可以利用@Order注解(或者实现Order接口)来规定所有CommandLineRunner实例的运行顺序。
 
例子:
 1 @EnableAsync
 2 @EnableSwagger2Doc
 3 @SpringBootApplication
 4 public class App implements CommandLineRunner,Common{
 5     @Autowired
 6     private ApplicationContext appContext;
 7     
 8     public static void main(String[] args) throws Exception {
 9         Logger.info("Server Loading Start:");
10         /**
11          * mybatis初始化
12          */
13         DbCache.instance();
14         
15         DataCache.init();
16 
17         /**
18          * *开启service服务
19          */
20         SpringApplication.run(App.class, args);
21         
22         Logger.info("Server Loading end:");
23         
24     }
25     
26     @Override
27     public void run(String... args) throws Exception {
28         String[] beans = appContext.getBeanDefinitionNames();
29         for (String bean : beans) {
30             HttpInterface.loadInterface(appContext.getBean(bean).getClass());
31         }
32     }
33 }

 

posted @ 2020-10-09 11:44  杨斌_济南  阅读(369)  评论(0编辑  收藏  举报