LoginSignup
6
4

More than 5 years have passed since last update.

Spring BootのSpring BatchでのCommandLineRunnerの使われ方

Posted at

Spring Bootでコンソールアプリケーション作るやり方を調べたところ、reference guide読む感じだとCommandLineRunnerApplicationRunnerを使う、と書いてある。

ところで、CommandLineRunnerの実装クラスをなんとなく調べたらJobLauncherCommandLineRunnerというSpring BootでSpring Batchを動かすためのクラスがあった。このクラスのデフォルト動作はそのコンテキスト内のすべてのJobを実行する。ただし、jobNameを指定することで特定のジョブを実行することもできる、と書いてある。この実装どうやってるのか気になったので、該当部分のソースを見てみた。

JobLauncherCommandLineRunner
public class JobLauncherCommandLineRunner
    implements CommandLineRunner, ApplicationEventPublisherAware {

    @Autowired(required = false)
    public void setJobs(Collection<Job> jobs) {
        this.jobs = jobs;
    }

    @Override
    public void run(String... args) throws JobExecutionException {
        logger.info("Running default command line with: " + Arrays.asList(args));
        launchJobFromProperties(StringUtils.splitArrayElementsIntoProperties(args, "="));
}


    private void executeLocalJobs(JobParameters jobParameters)
            throws JobExecutionException {
        for (Job job : this.jobs) {
            if (StringUtils.hasText(this.jobNames)) {
                String[] jobsToRun = this.jobNames.split(",");
                if (!PatternMatchUtils.simpleMatch(jobsToRun, job.getName())) {
                    logger.debug("Skipped job: " + job.getName());
                    continue;
                }
            }
            execute(job, jobParameters);
        }
}

Spring Boot起動後にCommandLineRunnerrunメソッドが実行される。ここの実装でジョブを起動している。また、setJbosのインジェクションですべてのJobのコレクションが入れられる。次にexecuteLocalJobsメソッドで、そのすべてのJobをいっこずつ起動している。その際、もしjobNameの指定があればマッチするジョブだけ起動して他はスキップしている。

コンソールアプリで何らかのキーで特定の機能だけ実行するのってどうやるんかな~CommandLineRunnerが複数あっても全部実行されるしな~と思ってたけど、こんな作りにすればよさそう。

6
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
6
4