啓動後執行
Spring Boot啓動後執行,有兩個接口可以實現
ApplicationRunner
實現ApplicationRunner接口可以在容器程序啓動後執行。
@Component
public class ApplicationRunnerImpl implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("通過實現ApplicationRunner接口,在spring boot項目啓動後打印參數");
String[] sourceArgs = args.getSourceArgs();
for (String arg : sourceArgs) {
System.out.print(arg + " ");
}
System.out.println();
}
}
CommandLineRunner接口
實現CommandLineRunner接口也可以實現程序啓動後執行。
@Component
public class CommandLineRunnerImpl implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("通過實現CommandLineRunner接口,在spring boot項目啓動後打印參數");
for (String arg : args) {
System.out.print(arg + " ");
}
System.out.println();
}
}
當項目中同時實現了ApplicationRunner和CommondLineRunner接口時,可使用@Order或實現Ordered接口來指定執行順序,值越小越先執行
原理
執行 org.springframework.boot.SpringApplication#run(java.lang.String…) 方法內的 afterRefresh(上下文刷新後處理)方法時,會執行callRunners方法。
afterRefresh方法如下:
protected void afterRefresh(ConfigurableApplicationContext context,
ApplicationArguments args) {
callRunners(context, args);
}
callRunners方法如下:
private void callRunners(ApplicationContext context, ApplicationArguments args) {
List<Object> runners = new ArrayList<Object>();
runners.addAll(context.getBeansOfType(ApplicationRunner.class).values());
runners.addAll(context.getBeansOfType(CommandLineRunner.class).values());
AnnotationAwareOrderComparator.sort(runners);
for (Object runner : new LinkedHashSet<Object>(runners)) {
if (runner instanceof ApplicationRunner) {
callRunner((ApplicationRunner) runner, args);
}
if (runner instanceof CommandLineRunner) {
callRunner((CommandLineRunner) runner, args);
}
}
}
依次調用ApplicationRunner和CommandLineRunner。
Spring MVC實現啓動時調用的方法有很多,比如:
實現ApplicationListener接口
@Service
public class StartupListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent evt) {
sout("ContextRefreshedEvent!")
}
}
ApplicationContext事件機制是觀察者設計模式的實現,通過ApplicationEvent類和ApplicationListener接口,可以實現ApplicationContext事件處理。
內置的ApplicationEvent有:
- ContextRefreshedEvent :ApplicationContext 被初始化或刷新時,該事件被髮布。
- ContextStartedEvent : 當使用 ConfigurableApplicationContext (ApplicationContext子接口)接口中的 start() 方法啓動 ApplicationContext 時,該事件被髮布
- ContextStoppedEvent :當使用 ConfigurableApplicationContext 接口中的 stop() 停止 ApplicationContext 時,發佈這個事件。
- ContextClosedEvent :當使用 ConfigurableApplicationContext 接口中的 close() 方法關閉 ApplicationContext 時,該事件被髮布。
- RequestHandledEvent :這是一個 web-specific 事件,告訴所有 bean HTTP 請求已經被服務。只能應用於使用DispatcherServlet的Web應用。在使用Spring作爲前端的MVC控制器時,當Spring處理用戶請求結束後,系統會自動觸發該事件。
也可以自定義事件。