Spring Batch で用意されている Event Listener も色々あるが、とりあえず Job の実行前後で起動する JobListener を使ってログを吐いてみよう。
「一番シンプルな Spring Batch 6 の Chunk 処理例」で作ったバッチ処理に足してみる。
■LogJobListener.java の作成
JobExecutionListener を実装した Job の前後にログを吐くクラス。beforeJob に Job の前の処理を、afterJob に後の処理を書く。
package com.netandfield.test.Listener;import org.springframework.batch.core.job.JobExecution;import org.springframework.batch.core.listener.JobExecutionListener;import org.springframework.stereotype.Component;import lombok.extern.slf4j.Slf4j;@Component@Slf4jpublic class LogJobListener implements JobExecutionListener {@Overridepublic void beforeJob(JobExecution jobExecution) {log.info("★Job started: " + jobExecution.getJobInstance().getJobName());}@Overridepublic void afterJob(JobExecution jobExecution) {log.info("★Job finished: " + jobExecution.getJobInstance().getJobName() + " with status: " + jobExecution.getStatus());}}
■BatchConfig.java
バッチ設定に Listener をセットする
import部に、
import org.springframework.batch.core.listener.JobExecutionListener;import org.springframework.beans.factory.annotation.Autowired;
を追加。
メンバ変数に jobListener を宣言。
<略>@Configurationpublic class BatchConfig {private final JobRepository jobRepository;private final PlatformTransactionManager transactionManager;private final DataSource dataSource;@Autowiredprivate JobExecutionListener jobListener;<略>
Jobの定義に JobListener を追加する
@Beanpublic Job exportJob() {return new JobBuilder("exportJob", jobRepository).start(exportStep()).listener(jobListener) // JobExecutionListenerを追加.build();}
ここまでソースをを修正したら実行。
これで、以下のようなログが出力される(長いので頭の方を「~」と略している)
...~ : Job: [SimpleJob: [name=exportJob]] launched with the following parameters: [{}]~ : ★Job started: exportJob~ : Executing step: [exportStep]~ : Step: [exportStep] executed in 681ms~ : ★Job finished: exportJob with status: COMPLETED~ : Job: [SimpleJob: [name=exportJob]] completed with the following parameters: [{}] and the following status: [COMPLETED] in 698ms...
ちゃんと出てるね。
ちなみにバッチ処理では「ボタンをクリックした」「表示されているオブジェクトにオンマウスした」などのイベントは無いので、用意されている Listener はほとんど「〇〇処理の前後に起動する」ものだ。
反対に、なんらかの処理には全て Listener が用意されている・・・かな。
「Stepの実行前後」「Chunkの実行前後とエラー発生時」「Readerの実行前後とエラー発生時」等など。

コメントする