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); }

}

 

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

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

CommandLineRunner接口可以用来接收字符串数组的命令行参数,ApplicationRunner 是使用ApplicationArguments 用来接收参数的,貌似后者更牛逼一些。

先看看CommandLineRunner :

  1. package com.springboot.study;
  2.  
  3. import org.springframework.boot.CommandLineRunner;
  4. import org.springframework.stereotype.Component;
  5.  
  6. /**
  7. * Created by pangkunkun on 2017/9/3.
  8. */
  9. @Component
  10. public class MyCommandLineRunner implements CommandLineRunner{
  11.  
  12. @Override
  13. public void run(String... var1) throws Exception{
  14. System.out.println("This will be execute when the project was started!");
  15. }
  16. }
  •  

ApplicationRunner :

  1. package com.springboot.study;
  2.  
  3. import org.springframework.boot.ApplicationArguments;
  4. import org.springframework.boot.ApplicationRunner;
  5. import org.springframework.stereotype.Component;
  6.  
  7. /**
  8. * Created by pangkunkun on 2017/9/3.
  9. */
  10. @Component
  11. public class MyApplicationRunner implements ApplicationRunner {
  12.  
  13. @Override
  14. public void run(ApplicationArguments var1) throws Exception{
  15. System.out.println("MyApplicationRunner class will be execute when the project was started!");
  16. }

 

http://note.youdao.com/noteshare?id=55c22c6e331f1b8106d24f21c21d6737&sub=925853C664224D70BBFDDB6C4B27A408

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值