zoukankan      html  css  js  c++  java
  • Springboot 项目启动后执行某些自定义代码

    Springboot给我们提供了两种“开机启动”某些方法的方式:ApplicationRunner和CommandLineRunner。  

    这两种方法提供的目的是为了满足,在项目启动的时候立刻执行某些方法。我们可以通过实现ApplicationRunner和CommandLineRunner,来实现,他们都是在SpringApplication 执行之后开始执行的。  

    CommandLineRunner接口可以用来接收字符串数组的命令行参数,ApplicationRunner 是使用ApplicationArguments 用来接收参数的

    代码示例

    @Component//被spring容器管理  
    @Order(1)//如果多个自定义ApplicationRunner,用来标明执行顺序  
    public class MyApplicationRunner implements ApplicationRunner {  
        @Override  
        public void run(ApplicationArguments applicationArguments) throws Exception {  
            System.out.println("-------------->" + "项目启动,now=" + new Date());  
            myTimer();  
        }  
      
        public static void myTimer(){  
            Timer timer = new Timer();  
            timer.schedule(new TimerTask() {  
                @Override  
                public void run() {  
                    System.out.println("------定时任务--------");  
                }  
            }, 0, 1000);  
        }  
    }
    

      执行结果

    2018-02-08 14:10:16.490  INFO 10236 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8081 (http)  

    -------------->项目启动,now=Thu Feb 08 14:10:16 CST 2018  

    ------定时任务--------  2018-02-08 14:10:16.497  INFO 10236 --- [           main] com.mlxs.springboot01.web.MainApp        : Started MainApp in 5.595 seconds (JVM running for 6.334)  

    ------定时任务--------  

    ------定时任务--------  

    ------定时任务--------  

    ------定时任务--------  

    ------定时任务--------  

    ------定时任务--------  

  • 相关阅读:
    联想 thinkpad 双系统 linux
    日期差值 1096
    np.newaxis用法详解
    Tensorflow InternalError: Blas SGEMM launch failed
    [转载] xmapp启动Tomcat时报JDK、JRE未安装错误的解决方法
    opensuse 装机总结
    opensuse nvidia 解决方案 [转载]
    驱动调试方法
    模块加载——modprobe和insmod的区别(转)
    UBOOT2016.05 看门狗
  • 原文地址:https://www.cnblogs.com/DreamFather/p/11327396.html
Copyright © 2011-2022 走看看