SpringBoot启动时任务,实现ApplicationRunner和CommandLineRunner接口的简单分析

我们都知道,springboot做初始化任务的时候可以实现ApplicationRunnerCommandLineRunner接口,重写run方法来完成。

public class MyStarter1 implements ApplicationRunner {

    @Override
    public void run(ApplicationArguments args) throws Exception {
    	// do something
    }
}
public class MyStarter2 implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
		// do something
    }
}

可以看到,虽然都是run方法,但是参数是不同的。这里通过源码看一下这两者的区别。

首先是CommandLineRunner,查看源码

package org.springframework.boot;

@FunctionalInterface
public interface CommandLineRunner {
    void run(String... args) throws Exception;
}

发现除了我们自定义的实现,该接口没有任何实现,那么说明,这个接口的功能就是为了在程序启动时方便开发人员做一些初始化的操作。

再看ApplicationRunner,查看源码

@FunctionalInterface
public interface ApplicationRunner {
    void run(ApplicationArguments args) throws Exception;
}

此类有内部实现JobLauncherApplicationRunner

public class JobLauncherApplicationRunner implements ApplicationRunner, Ordered, ApplicationEventPublisherAware {
    
	// ....
    
    // 入口
    public void run(ApplicationArguments args) throws Exception {
        String[] jobArguments = (String[])args.getNonOptionArgs().toArray(new String[0]);
        this.run(jobArguments);
    }
    // 调用此方法
    protected void launchJobFromProperties(Properties properties) throws JobExecutionException {
        JobParameters jobParameters = this.converter.getJobParameters(properties);
        // 执行任务
        this.executeLocalJobs(jobParameters);
        // 注册任务
        this.executeRegisteredJobs(jobParameters);
    }
    // 执行任务调用此方法
    protected void execute(Job job, JobParameters jobParameters) throws JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobParametersInvalidException, JobParametersNotFoundException {
        JobParameters parameters = this.getNextJobParameters(job, jobParameters);
        JobExecution execution = this.jobLauncher.run(job, parameters);
        // 发布事件
        if (this.publisher != null) {
            this.publisher.publishEvent(new JobExecutionEvent(execution));
        }

    }
}

看一下传入的JobExecutionEvent,实现了ApplicationEvent

public class JobExecutionEvent extends ApplicationEvent {
    private final JobExecution execution;

    public JobExecutionEvent(JobExecution execution) {
        super(execution);
        this.execution = execution;
    }

    public JobExecution getJobExecution() {
        return this.execution;
    }
}

从上面的源码可以看出,CommandLineRunner的作用比较单纯,就是执行一个启动时任务,没有做什么额外的事情。ApplicationRunner则功能更丰富一点,可以把它的run方法当作一个任务,该任务会被注册到容器内,通过ApplicationListener监听可以捕捉到这个任务的执行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值