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 :
- package com.springboot.study;
- import org.springframework.boot.CommandLineRunner;
- import org.springframework.stereotype.Component;
- /**
- * Created by pangkunkun on 2017/9/3.
- */
- @Component
- public class MyCommandLineRunner implements CommandLineRunner{
- @Override
- public void run(String... var1) throws Exception{
- System.out.println("This will be execute when the project was started!");
- }
- }
ApplicationRunner :
- package com.springboot.study;
- import org.springframework.boot.ApplicationArguments;
- import org.springframework.boot.ApplicationRunner;
- import org.springframework.stereotype.Component;
- /**
- * Created by pangkunkun on 2017/9/3.
- */
- @Component
- public class MyApplicationRunner implements ApplicationRunner {
- @Override
- public void run(ApplicationArguments var1) throws Exception{
- System.out.println("MyApplicationRunner class will be execute when the project was started!");
- }