springboot拓展接口ApplicationRunner和CommandLineRunner详解

使用场景

在springboot应用启动后做一些操作,比如读取字典表数据到缓存中。

看看源码

/**
 * Interface used to indicate that a bean should <em>run</em> when it is contained within
 * a {@link SpringApplication}. Multiple {@link ApplicationRunner} beans can be defined
 * within the same application context and can be ordered using the {@link Ordered}
 * interface or {@link Order @Order} annotation.
 *
 * @author Phillip Webb
 * @since 1.3.0
 * @see CommandLineRunner
 */
@FunctionalInterface
public interface ApplicationRunner {

    /**
     * Callback used to run the bean.
     * @param args incoming application arguments
     * @throws Exception on error
     */
    void run(ApplicationArguments args) throws Exception;

}
/**
 * Interface used to indicate that a bean should <em>run</em> when it is contained within
 * a {@link SpringApplication}. Multiple {@link CommandLineRunner} beans can be defined
 * within the same application context and can be ordered using the {@link Ordered}
 * interface or {@link Order @Order} annotation.
 * <p>
 * If you need access to {@link ApplicationArguments} instead of the raw String array
 * consider using {@link ApplicationRunner}.
 *
 * @author Dave Syer
 * @since 1.0.0
 * @see ApplicationRunner
 */
@FunctionalInterface
public interface CommandLineRunner {

    /**
     * Callback used to run the bean.
     * @param args incoming main method arguments
     * @throws Exception on error
     */
    void run(String... args) throws Exception;

}

看看代码示例

实现这两个接口并重写run方法,那么在项目启动完成run方法中的代码将自动执行,可以使用@Order注解或实现Ordered接口控制多个Runner的执行顺序,并可以通过ApplicationRunner的参数ApplicationArguments和CommandLineRunner的参数String...获取命令行参数。

@Component
@Order(1)
public class MyApplicationRunner implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("MyApplicationRunner run ...");
        System.out.println(JSON.toJSONString(args));
    }
}
@Component
public class MyCommandLineRunner implements CommandLineRunner, Ordered {

    @Override
    public void run(String... args) throws Exception {
        System.out.println("MyCommandLineRunner run ...");
        System.out.println(JSON.toJSONString(args));
    }

    @Override
    public int getOrder() {
        return 1;
    }
}

看看效果

启动项目

查看控制台输出

 

posted @ 2021-03-11 17:42  mgyboom  阅读(232)  评论(0编辑  收藏  举报