zoukankan      html  css  js  c++  java
  • 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;
        }
    }

    看看效果

    启动项目

    查看控制台输出

  • 相关阅读:
    Spring set注入
    Spring 搭建
    MyBatis 动态Sql
    Mybatis 数据读取
    MyBatis 搭建
    第三十二章:Map集合
    第三十一章:集合输出
    第三十章:Set集合
    第二十八、九章:类集框架简介、List集合
    第25、26、27章:类加载器、反射与代理设计模式、反射与Annotation
  • 原文地址:https://www.cnblogs.com/mgyboom/p/14519380.html
Copyright © 2011-2022 走看看