程序在启动完成的时候可能需要去处理某些业务,Spring Boot程序中可以通过去实现CommandLineRunner和ApplicationRunner接口还完成该操作。
在重新run方法未执行完成时,对外不访问而言程序不可以访问【spring 容器并未完成初始化】。
一些简单记录无业务影响的操作应该使用异步操作。
- /**
- * Application类
- */
- @SpringBootApplication
- public class DemoApplication implements CommandLineRunner {
-
- @Resource
- private DemoService deomService;
-
- public static void main(String[] args) {
- System.out.println("容器开始创建");
- SpringApplication.run(DemoApplication .class, args);
- System.out.println("容器创建完成");
- }
-
- @Override
- public void run(String... args) throws Exception {
- System.out.println("容器创建完成?,先执行下列操作:");
- // TODO
- deomService.sayHello();
- }
-
- }
多个业务顺序执行
- @Component
- @Order(1)
- public class UserRunner implements CommandLineRunner {
-
- public void run(String... args) throws Exception {
- System.out.println("UserRunner run");
-
- Thread.sleep(1000);
- }
-
- }
-
-
- @Component
- @Order(2)
- public class OrderRunner implements CommandLineRunner {
-
- public void run(String... args) throws Exception {
- System.out.println("OrderRunner run");
-
- Thread.sleep(1000);
- }
-
- }
简单使用 【启动类直接实现CommandLineRunner】
- /**
- * Application类
- */
- @SpringBootApplication
- public class DemoApplication implements ApplicationRunner {
-
- @Resource
- private DemoService deomService;
-
- public static void main(String[] args) {
- System.out.println("容器开始创建");
- SpringApplication.run(DemoApplication .class, args);
- System.out.println("容器创建完成");
- }
-
- @Override
- public void run(ApplicationArguments args) throws Exception {
- System.out.println("容器创建完成?,先执行下列操作:");
- // TODO
- deomService.sayHello();
- }
-
- }
多个业务顺序执行
- @Component
- @Order(1)
- public class UserRunner implements ApplicationRunner {
-
- @Override
- public void run(ApplicationArguments args) throws Exception {
- System.out.println("UserRunner run");
-
- Thread.sleep(1000);
- }
-
-
- }
-
- @Component
- @Order(2)
- public class OrderRunner implements ApplicationRunner {
-
- @Override
- public void run(ApplicationArguments args) throws Exception {
- System.out.println("UserRunner run");
-
- Thread.sleep(1000);
- }
-
- }
看起来是不是没啥区别哈?
主要不同就是ApplicatioinRunner的run()方法的参数ApplicationArguments可以很方便地获取到命令行参数的值。
浅见 如果出入希望大家留言