SpringバッチHello Worldの例

Spring Batch Hello Worldの例

Spring Batchは、バッチ処理(一連のジョブの実行)のフレームワークです。 Spring Batchでは、ジョブは多くのステップで構成され、各ステップはREAD-PROCESS-WRITEタスクまたは `+単一操作+`タスク(タスクレット)で構成されます。

  1. 「READ-PROCESS-WRITE」プロセスの場合、リソース(csv、xmlまたはデータベース)からデータを「読み取り」、「処理」し、他のリソース(csv、xmlおよびデータベース)に「書き込む」ことを意味します。 たとえば、ステップはCSVファイルからデータを読み取り、それを処理してデータベースに書き込むことができます。 Spring Batchは、CSV、XML、およびデータベースを読み書きするための多くのクラスを提供します。

  2. 「単一」操作タスク(タスクレット)の場合、ステップが開始または完了した後または前にリソースをクリーンアップするなど、単一のタスクのみを実行することを意味します。

  3. そして、ジョブとして実行するために、ステップを連鎖させることができます。

1 Job = Many Steps.
1 Step = 1 READ-PROCESS-WRITE or 1 Tasklet.
Job = {Step 1 -> Step 2 -> Step 3} (Chained together)

Spring Batchの例

次のバッチジョブを検討してください。

  1. ステップ1-CSVファイルをフォルダーAから読み取り、処理し、フォルダーBに書き込みます。 「読み取りプロセス書き込み」

  2. ステップ2-フォルダーBからCSVファイルを読み取り、処理し、データベースに書き込みます。 「読み取りプロセス書き込み」

  3. ステップ3-フォルダーBからCSBファイルを削除します。 「タスクレット」

  4. ステップ4 –データベースからデータを読み取り、XML形式で統計レポートを処理および生成し、フォルダーCに書き込みます。 「読み取りプロセス書き込み」

  5. ステップ5 –レポートを読んで、マネージャーのメールに送信します。 「タスクレット」

Spring Batchでは、次のように宣言できます:

  
    
      
        
      
    
    
      
        
      
    
    
      
    
    
      
        
      
    
    
        
    
  

ジョブとステップの実行全体がデータベースに保存されるため、失敗したステップは失敗した場所から再開でき、ジョブ全体をやり直す必要はありません。

1. チュートリアル

このSpring Batchチュートリアルでは、ジョブの作成、CSVファイルの読み取り、処理、XMLファイルへの出力の書き込み方法を示します。

使用するツールとライブラリ

  1. メーベン3

  2. Eclipse 4.2

  3. JDK 1.6

  4. Spring Core 3.2.2.RELEASE

  5. Spring OXM 3.2.2.RELEASE

  6. Spring JDBC 3.2.2.RELEASE

  7. Spring Batch 2.2.0.RELEASE

2. プロジェクトディレクトリ

標準のMavenプロジェクトである最終プロジェクトディレクトリを確認します。

spring-batch-hello-world-directory

3. プロジェクトの依存関係

依存関係は、Spring Core、Spring Batch、およびJDK 1.5のみである必要があります。 自明のコメントを読んでください。

pom.xml


    4.0.0
    com.example
    SpringBatchExample
    jar
    1.0-SNAPSHOT
    SpringBatchExample
    http://maven.apache.org

    
        1.6
        3.2.2.RELEASE
        2.2.0.RELEASE
        5.1.25
        4.11
    

    

        
        
            org.springframework
            spring-core
            ${spring.version}
        

        
        
            org.springframework
            spring-jdbc
            ${spring.version}
        

        
        
            org.springframework
            spring-oxm
            ${spring.version}
        

        
        
            mysql
            mysql-connector-java
            ${mysql.driver.version}
        

        
        
            org.springframework.batch
            spring-batch-core
            ${spring.batch.version}
        
        
            org.springframework.batch
            spring-batch-infrastructure
            ${spring.batch.version}
        

        
        
            org.springframework.batch
            spring-batch-test
            ${spring.batch.version}
        

        
        
            junit
            junit
            ${junit.version}
            test
        

    
    
        spring-batch
        
            
                org.apache.maven.plugins
                maven-eclipse-plugin
                2.9
                
                    true
                    false
                
            
            
                org.apache.maven.plugins
                maven-compiler-plugin
                2.3.2
                
                    ${jdk.version}
                    ${jdk.version}
                
            
        
    

4. 春のバッチジョブ

CSVファイル。

report.csv

1001,"213,100",980,"example", 29/7/2013
1002,"320,200",1080,"staff 1", 30/7/2013
1003,"342,197",1200,"staff 2", 31/7/2013

Springバッチジョブは、上記のcsvファイルをFlatFileItemReaderで読み取り、データをitemProcessorで処理し、それをXMLファイル
StaxEventItemWriterで書き込みます。

job-hello-world.xml



    
    

    
    

    
      
        
            
            
        
      
    

    

        

        
            
            
                
                    
                
            
            
                

                 
            
            
        

    

    
        
        
        
    

    
       
        
            com.example.model.Report
        
        
    

CSV値をReportオブジェクトにマップし、それをXMLファイルに書き込みます(jaxbアノテーションを介して)。

Report.java

package com.example.model;

import java.math.BigDecimal;
import java.util.Date;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "record")
public class Report {

    private int id;
    private BigDecimal sales;
    private int qty;
    private String staffName;
    private Date date;

    @XmlAttribute(name = "id")
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @XmlElement(name = "sales")
    public BigDecimal getSales() {
        return sales;
    }

    public void setSales(BigDecimal sales) {
        this.sales = sales;
    }

    @XmlElement(name = "qty")
    public int getQty() {
        return qty;
    }

    public void setQty(int qty) {
        this.qty = qty;
    }

    @XmlElement(name = "staffName")
    public String getStaffName() {
        return staffName;
    }

    public void setStaffName(String staffName) {
        this.staffName = staffName;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    @Override
    public String toString() {
        return "Report [id=" + id + ", sales=" + sales
                    + ", qty=" + qty + ", staffName=" + staffName + "]";
    }

}

Dateを変換するには、カスタムFieldSetMapperが必要です。 データ型変換がない場合は、BeanWrapperFieldSetMapperを使用して、値を名前で自動的にマップします。

ReportFieldSetMapper.java

package com.example;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.validation.BindException;

import com.example.model.Report;

public class ReportFieldSetMapper implements FieldSetMapper {

    private SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");

    @Override
    public Report mapFieldSet(FieldSet fieldSet) throws BindException {

        Report report = new Report();
        report.setId(fieldSet.readInt(0));
        report.setSales(fieldSet.readBigDecimal(1));
        report.setQty(fieldSet.readInt(2));
        report.setStaffName(fieldSet.readString(3));

        //default format yyyy-MM-dd
        //fieldSet.readDate(4);
        String date = fieldSet.readString(4);
        try {
            report.setDate(dateFormat.parse(date));
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return report;

    }

}

itemWriterの前にitemProcessorが起動されます。

CustomItemProcessor.java

package com.example;

import org.springframework.batch.item.ItemProcessor;
import com.example.model.Report;

public class CustomItemProcessor implements ItemProcessor {

    @Override
    public Report process(Report item) throws Exception {

        System.out.println("Processing..." + item);
        return item;
    }

}

Springコンテキストとデータベース構成。

context.xml



    
    

     
    
        
        
        
    

    

    
        
    

database.xml



        
    
        
        
        
        
    

    

    
    
        
        
    

5. それを実行します

バッチジョブを実行する最も簡単な方法。

package com.example;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {
  public static void main(String[] args) {

    String[] springConfig  =
        {
            "spring/batch/jobs/job-hello-world.xml"
        };

    ApplicationContext context =
            new ClassPathXmlApplicationContext(springConfig);

    JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
    Job job = (Job) context.getBean("helloWorldJob");

    try {

        JobExecution execution = jobLauncher.run(job, new JobParameters());
        System.out.println("Exit Status : " + execution.getStatus());

    } catch (Exception e) {
        e.printStackTrace();
    }

    System.out.println("Done");

  }
}

出力

report.xml


    
        2013-07-29T00:00:00+08:00
        980
        213100
        example
    
    
        2013-07-30T00:00:00+08:00
        1080
        320200
        staff 1
    
    
        2013-07-31T00:00:00+08:00
        1200
        342197
        staff 2
    

コンソールで

Jul 30, 2013 11:52:00 PM org.springframework.batch.core.launch.support.SimpleJobLauncher$1 run
INFO: Job: [FlowJob: [name=helloWorldJob]] launched with the following parameters: [{}]
Jul 30, 2013 11:52:00 PM org.springframework.batch.core.job.SimpleStepHandler handleStep
INFO: Executing step: [step1]
Processing...Report [id=1001, sales=213100, qty=980, staffName=example]
Processing...Report [id=1002, sales=320200, qty=1080, staffName=staff 1]
Processing...Report [id=1003, sales=342197, qty=1200, staffName=staff 2]
Jul 30, 2013 11:52:00 PM org.springframework.batch.core.launch.support.SimpleJobLauncher$1 run
INFO: Job: [FlowJob: [name=helloWorldJob]] completed with the following parameters: [{}] and the following status: [COMPLETED]
Exit Status : COMPLETED
Done

ソースコードをダウンロード

ダウンロード–SpringBatch-Hello-World-Example.zip(27 kb)