1、快速创建项目
Spring Initalizr 快速创建项目,引入task依赖,示例如下:
2、修改代码
代码如下:
package com.example.Task;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class TaskApplication {
@Bean
public MyTask myTask()
{
return new MyTask();
}
public static void main(String[] args) {
SpringApplication.run(TaskApplication.class, args);
}
public static class MyTask implements CommandLineRunner
{
@Override
public void run(String... args) throws Exception {
System.out.println("This is my first task application!");
}
}
}运行main方法,控制台可打印”This is my first task application!“信息。我们发现,任务结束后,服务关闭,线程结束。
3、原理解析
通过以上简单实例,我们可看出 CommandLineRunner 是springcloud task实现的一个关键。 查看CommandLineRunner是一个接口,以下为其注释:
Interface used to indicate that a bean should run 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.
If you need access to {@link ApplicationArguments} instead of the raw String array
consider using {@link ApplicationRunner}.从接口注释中,我们知道,CommandLineRunner是一个接口,其用来表明当一个spring应用程序包含包含CommandLineRunner类型的bean时,这个bean会被执行。
同一个应用上下文中可以定义多个CommandLineRunner的bean,可使用Ordered接口或@Order注解标注其顺序。
最后,我们可以看到,如果你需要输入ApplicationArguments类型的参数,而不是字符串数组时,可以考虑使用ApplicationRunner接口。这句话表明,我们也可以使用ApplicationRunner接口替换CommandLineRunner接口,此时我们的任务也可以实现,只不过接口中run方法的参数不一样罢了。