CommandLineRunner接口会在容器启动成功后被回调。若有多个自定义CommandLineRunner接口,我们可以通过@Order注解/实现Ordered接口控制它们执行的先后顺序
实现步骤
1)编写CommandLineRunner
实现类,将其加入spring容器中
@Component
public class ServerSuccessReport implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("======应用启动成功======");
}
}
2)执行BlogApplication
@SpringBootApplication
public class BlogApplication {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(BlogApplication.class);
ConfigurableApplicationContext context = springApplication.run(args);
context.close();
}
}
我们看到,当输出
======应用启动成功======
后,应用提示我们花费了9s时间,然后因为我们执行了context.close()
方法,应用提示我们正在关闭。我们会发现,CommandLineRunner接口的确是在容器初始化成功后被回调的。
@Order
定义CommandLineRunner
执行顺序
这个较为简单,本文不多描述,@Order
注解中的数越小,执行的优先级越高