SpingBoot之ApplicationRunner和CommandLineRunner

杀马特。学长 韩版系。学妹 提交于 2019-12-04 18:30:04

ApplicationRunner和CommandLineRunner

    如果你需要在SpringApplication启动后执行特殊的代码,你可以实现ApplicationRunner或CommandLineRunner接口,这两个接口工作方式基本上一样,都是提供单一的run方法,该方法是在容器启动完成的时候执行,而CommandLineRunner接口能够访问string数组类型的应用参数,而ApplicationRunner使用的是上面描述过的ApplicationArguments接口。

源码

ApplicationRunner

@FunctionalInterface
public interface ApplicationRunner {
    void run(ApplicationArguments args) throws Exception;
}

CommandLineRunner

@FunctionalInterface
public interface CommandLineRunner {
    void run(String... args) throws Exception;
}

如何指定Bean的初始化顺序?

    如果很多定义实现可CommandLineRunner或ApplicationRunner的beans需要指定顺序调用,可以实现org.springframework.core.Ordered接口或使用org.springframework.core.annotation.Order注解,比如:

@Component
    @Order(2)
    public class MyBean1 implements CommandLineRunner{
        @Override
        public void run(String... args) throws Exception {
            System.out.println("MyBean1初始化了....");
        }
    }

    @Component
    @Order(1)
    public class MyBean2 implements CommandLineRunner{
        @Override
        public void run(String... args) throws Exception {
            System.out.println("MyBean2初始化了....");
        }
    }

运行Application主程序,控制台输出结果:

结论:Order值越小,越先执行。

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!