Spring-batch-quick-guide

提供:Dev Guides
移動先:案内検索

Spring Batch-概要

  • バッチ処理*は、ユーザーの操作なしで一連の自動化された複雑なジョブを実行する処理モードです。 バッチプロセスはバルクデータを処理し、長時間実行されます。

いくつかのエンタープライズアプリケーションは、関連する操作を実行するために巨大なデータを処理する必要があります-

  • 定期的な計算などの時間ベースのイベント。
  • 大規模なデータセットで繰り返し処理される定期的なアプリケーション。
  • トランザクション方式で利用可能なデータの処理と検証を扱うアプリケーション。

したがって、エンタープライズアプリケーションでは、このようなトランザクションを実行するためにバッチ処理が使用されます。

Spring Batchとは

Springバッチは、エンタープライズアプリケーションで使用される*バッチアプリケーション*の開発に使用される*軽量フレームワーク*です。

バルク処理に加えて、このフレームワークはのための機能を提供します-

  • ロギングとトレースを含む
  • トランザクション管理
  • ジョブ処理統計
  • ジョブの再起動
  • スキップおよびリソース管理

分割手法を使用して、スプリングバッチアプリケーションをスケーリングすることもできます。

Spring Batchの機能

以下は、Spring Batchの注目すべき機能です-

  • 柔軟性-Spring Batchアプリケーションは柔軟性があります。 アプリケーションでの処理の順序を変更するには、XMLファイルを変更するだけです。
  • 保守性-Spring Batchアプリケーションは保守が簡単です。 Spring Batchジョブにはステップが含まれており、他のステップに影響を与えることなく、各ステップを分離、テスト、および更新できます。
  • スケーラビリティ-分割テクニックを使用して、Spring Batchアプリケーションをスケーリングできます。 これらの手法により、次のことが可能になります-
  • ジョブのステップを並行して実行します。
  • 単一のスレッドを並列で実行します。
  • 信頼性-障害が発生した場合、ステップを分離することにより、停止した場所からジョブを再開できます。
  • 複数のファイル形式のサポート-Spring Batchは、XML、フラットファイル、CSV、MYSQL、Hibernate、JDBC、Mongo、Neo4jなどの多数のリーダーとライターのサポートを提供します。
  • ジョブを起動する複数の方法-Webアプリケーション、Javaプログラム、コマンドラインなどを使用してSpring Batchジョブを起動できます。

これらに加えて、Spring Batchアプリケーションはサポートします-

  • 失敗後の自動再試行。
  • バッチ実行中およびバッチ処理完了後のステータスと統計の追跡。
  • 並行ジョブを実行します。
  • ロギング、リソース管理、スキップ、処理の再開などのサービス。

Spring Batch-環境

この章では、Eclipse IDEでSpring Batch環境を設定する方法について説明します。 インストールを続行する前に、システムにEclipseがインストールされていることを確認してください。 そうでない場合は、システムにEclipseをダウンロードしてインストールします。

Eclipseの詳細については、リンク:/eclipse/index [Eclipse Tutorial。]を参照してください。

EclipseでのSpring Batchの設定

以下の手順に従って、EclipseでSpring Batch環境を設定します。

  • ステップ1 *-Eclipseをインストールし、次のスクリーンショットに示すように新しいプロジェクトを開きます。

新しいプロジェクト

  • ステップ2 *-以下に示すように、サンプルのSpring Batchプロジェクトを作成します。

プロジェクト名

ステップ3 *-プロジェクトを右クリックして、以下に示すようにMavenプロジェクトに変換します。 Mavenプロジェクトに変換すると、 *Pom.xml が提供され、必要な依存関係について言及する必要があります。 その後、それらの jar ファイルが自動的にプロジェクトにダウンロードされます。

構成

ステップ4 *-次に、プロジェクトの *pom.xml で、次のコンテンツ(Spring Batchアプリケーションの依存関係)をコピーして貼り付け、プロジェクトを更新します。

<project xmlns = "http://maven.apache.org/POM/4.0.0"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0
   http://maven.apache.org/maven-v4_0_0.xsd">
   <modelVersion>4.0.0</modelVersion>
   <groupId>com.finddevguides</groupId>
   <artifactId>SpringBatchSample</artifactId>
   <packaging>jar</packaging>
   <version>1.0-SNAPSHOT</version>
   <name>SpringBatchExample</name>
   <url>http://maven.apache.org</url>

   <properties>
      <jdk.version>1.8</jdk.version>
      <spring.version>4.3.8.RELEASE</spring.version>
      <spring.batch.version>3.0.7.RELEASE</spring.batch.version>
      <mysql.driver.version>5.1.25</mysql.driver.version>
      <junit.version>4.11</junit.version>
   </properties>

   <dependencies>
      <!-- Spring Core -->
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-core</artifactId>
         <version>${spring.version}</version>
      </dependency>

      <!-- Spring jdbc, for database -->
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-jdbc</artifactId>
         <version>${spring.version}</version>
      </dependency>

      <!-- Spring XML to/back object -->
      <dependency>
         <groupId>org.springframework</groupId>
         <artifactId>spring-oxm</artifactId>
         <version>${spring.version}</version>
      </dependency>

      <!-- MySQL database driver -->
      <dependency>
         <groupId>mysql</groupId>
         <artifactId>mysql-connector-java</artifactId>
         <version>${mysql.driver.version}</version>
      </dependency>

      <!-- Spring Batch dependencies -->
      <dependency>
         <groupId>org.springframework.batch</groupId>
         <artifactId>spring-batch-core</artifactId>
         <version>${spring.batch.version}</version>
      </dependency>

      <dependency>
         <groupId>org.springframework.batch</groupId>
         <artifactId>spring-batch-infrastructure</artifactId>
         <version>${spring.batch.version}</version>
      </dependency>

      <!-- Spring Batch unit test -->
      <dependency>
         <groupId>org.springframework.batch</groupId>
         <artifactId>spring-batch-test</artifactId>
         <version>${spring.batch.version}</version>
      </dependency>

      <!-- Junit -->
      <dependency>
         <groupId>junit</groupId>
         <artifactId>junit</artifactId>
         <version>${junit.version}</version>
         <scope>test</scope>
      </dependency>
   </dependencies>

   <build>
      <finalName>spring-batch</finalName>
      <plugins>
         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-eclipse-plugin</artifactId>
            <version>2.9</version>
            <configuration>
               <downloadSources>true</downloadSources>
               <downloadJavadocs>false</downloadJavadocs>
            </configuration>
         </plugin>

         <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version>
            <configuration>
               <source>${jdk.version}</source>
               <target>${jdk.version}</target>
            </configuration>
         </plugin>
      </plugins>
   </build>
</project>

最後に、Mavenの依存関係を観察すると、必要なすべての jar ファイルがダウンロードされていることがわかります。

Jarファイル

Spring Batch-アーキテクチャ

以下は、Spring Batchのアーキテクチャを図で表したものです。 図に示すように、アーキテクチャには3つの主要コンポーネント、つまり*アプリケーション、バッチコア*、および*バッチインフラストラクチャ*が含まれています。

アーキテクチャ

アプリケーション-このコンポーネントには、すべてのジョブと、Spring Batchフレームワークを使用して記述したコードが含まれています。

*Batch Core* -このコンポーネントには、バッチジョブの制御と起動に必要なすべてのAPIクラスが含まれています。

バッチインフラストラクチャ-このコンポーネントには、アプリケーションコンポーネントとバッチコアコンポーネントの両方で使用されるリーダー、ライター、およびサービスが含まれています。

Spring Batchのコンポーネント

次の図は、Spring Batchのさまざまなコンポーネントと、それらが互いにどのように接続されているかを示しています。

コンポーネント

Job

Spring Batchアプリケーションでは、ジョブは実行されるバッチプロセスです。 中断することなく、最初から最後まで実行されます。 このジョブはさらにステップに分割されます(またはジョブにはステップが含まれます)。

XMLファイルまたはJavaクラスを使用して、Spring Batchでジョブを構成します。 次に、Spring BatchのジョブのXML設定を示します。

<job id = "jobid">
   <step id = "step1" next = "step2"/>
   <step id = "step2" next = "step3"/>
   <step id = "step3"/>
</job>

バッチジョブは、タグ<job> </job>内で構成されます。 id という名前の属性があります。 これらのタグ内で、ステップの定義と順序を定義します。

再起動可能-一般に、ジョブが実行されているときに、再起動しようとすると、再起動*と見なされ、再起動されます。 これを回避するには、以下に示すように *restartable 値を false に設定する必要があります。

<job id = "jobid" restartable = "false" >

</job>

Step

  • ステップ*は、ジョブを定義および実行するために必要な情報(その部分)を含むジョブの独立した部分です。

図で指定されているように、各ステップはItemReader、ItemProcessor(オプション)、ItemWriterで構成されています。 ジョブには1つ以上のステップが含まれる場合があります

リーダー、ライター、およびプロセッサー

  • itemリーダー*は特定のソースからSpring Batchアプリケーションにデータを読み込みますが、 item writer はSpring Batchアプリケーションから特定の宛先にデータを書き込みます。

アイテムプロセッサ*は、スプリングバッチに読み込まれたデータを処理する処理コードを含むクラスです。 アプリケーションが *"n" レコードを読み取る場合、プロセッサ内のコードは各レコードで実行されます。

リーダーとライターが指定されていない場合、 tasklet はSpringBatchのプロセッサとして機能します。 単一のタスクのみを処理します。 たとえば、MySQLデータベースからデータを読み取り、それを処理してファイル(フラット)に書き込む単純なステップを含むジョブを作成する場合、ステップは次を使用します-

  • MySQLデータベースから読み取る*リーダー*。
  • フラットファイルに書き込む*ライター*。
  • 希望どおりにデータを処理する*カスタムプロセッサ*。
<job id = "helloWorldJob">
   <step id = "step1">
      <tasklet>
         <chunk reader = "mysqlReader" writer = "fileWriter"
            processor = "CustomitemProcessor" ></chunk>
      </tasklet>
   </step>
</job>

Spring Batchは readerswriters の長いリストを提供します。 これらの事前定義されたクラスを使用して、それらのBeanを定義できます。 *読者*と*作家*については、今後の章で詳しく説明します。

JobRepository

Spring Batchのジョブリポジトリは、JobLauncher、Job、およびStepの実装にCreate、Retrieve、Update、Delete(CRUD)操作を提供します。 以下に示すように、XMLファイルでジョブリポジトリを定義します。

<job-repository id = "jobRepository"/>
*id* に加えて、いくつかのオプション(オプション)が利用可能です。 以下は、すべてのオプションとそのデフォルト値を使用したジョブリポジトリの構成です。
<job-repository id = "jobRepository"
   data-source = "dataSource"
   transaction-manager = "transactionManager"
   isolation-level-for-create = "SERIALIZABLE"
   table-prefix = "BATCH_"
   max-varchar-length = "1000"/>

インメモリリポジトリ-Spring Batchのドメインオブジェクトをデータベースに保持したくない場合は、以下に示すようにjobRepositoryのインメモリバージョンを設定できます。

<bean id = "jobRepository"
   class = "org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean ">
   <property name = "transactionManager" ref = "transactionManager"/>
</bean>

JobLauncher

JobLauncherは、指定されたパラメーターセット*でSpring Batchジョブを起動するインターフェイスです。 *SampleJoblauncher は、 JobLauncher インターフェイスを実装するクラスです。 JobLauncherの構成は次のとおりです。

<bean id = "jobLauncher"
   class = "org.springframework.batch.core.launch.support.SimpleJobLauncher">
   <property name = "jobRepository" ref = "jobRepository"/>
</bean>

JobInstance

*JobInstance* はジョブの論理的な実行を表します。ジョブを実行すると作成されます。 各ジョブインスタンスは、ジョブの名前と実行中に渡されるパラメーターによって区別されます。

JobInstanceの実行が失敗した場合、同じJobInstanceを再度実行できます。 したがって、各JobInstanceは複数のジョブを実行できます。

JobExecutionおよびStepExecution

JobExecutionとStepExecutionは、ジョブ/ステップの実行の表現です。 これらには、開始時刻(ジョブ/ステップの)、終了時刻(ジョブ/ステップの)などのジョブ/ステップの実行情報が含まれます。

Spring Batch-アプリケーション

このチュートリアルのほとんどすべての例には、次のファイルが含まれています-

  • 構成ファイル(XMLファイル)
  • タスクレット/プロセッサ(Javaクラス)
  • セッターとゲッターを持つJavaクラス(Javaクラス(bean))
  • マッパークラス(Javaクラス)
  • ランチャークラス(Javaクラス)

構成ファイル

構成ファイル(XML)には次が含まれています-

  • job および step 定義。
  • readers および writers を定義するBean。
  • JobLauncher、JobRepository、Transaction Manager、Data Sourceなどのコンポーネントの定義。

例では、理解を深めるために、これを job.xml ファイル(ジョブ、ステップ、リーダー、ライターを定義)と context.xml ファイル(ジョブランチャー、ジョブリポジトリ、トランザクションマネージャー、情報源)。

マッパークラス

マッパークラスは、リーダーに応じて、 row mapperfield set mapper などのインターフェイスを実装します。 リーダーからデータを取得し、 setter および getter メソッド(Java Bean)を使用してJavaクラスに設定するコードが含まれています。

Java Beanクラス

*setters* および *getters* (Java Bean)を持つJavaクラスは、複数の値を持つデータを表します。 ヘルパークラスとして機能します。 このクラスのオブジェクトの形式で、1つのコンポーネント(リーダー、ライター、プロセッサ)から他のコンポーネントにデータを渡します。

タスクレット/プロセッサ

Tasklet/processorクラスには、Spring Batchアプリケーションの処理コードが含まれています。 プロセッサは、読み取られたデータを含むオブジェクトを受け入れ、処理し、処理されたデータを(フォームオブジェクトで)返すクラスです。

ランチャークラス

このクラス(App.java)には、Spring Batchアプリケーションを起動するコードが含まれています。

アプリケーション

Spring Batch-設定

Spring Batchアプリケーションの作成中に、Spring Batch名前空間で提供されるXMLタグを使用して、ジョブ、ステップ、JobLauncher、JobRepository、Transaction Manager、リーダー、ライターを構成します。 したがって、以下に示すように、XMLファイルにこの名前空間を含める必要があります。

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:batch = "http://www.springframework.org/schema/batch"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/batch

   http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
   http://www.springframework.org/schema/bean
   http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

次のセクションでは、Spring Batchネームスペースで使用可能なさまざまなタグ、その属性、および例について説明します。

Job

このタグは、SpringBatchのジョブを定義/構成するために使用されます。 これには一連のステップが含まれており、JobLauncherを使用して起動できます。

このタグには、次の2つの属性があります-

S.No Attribute & Description
1

Id

ジョブのIDです。この属性に値を指定することは必須です。

2

restartable

これは、ジョブが再起動可能かどうかを指定するために使用される属性です。 この属性はオプションです。

以下は、SpringBatchのジョブのXML構成です。

<job id = "jobid" restartable = "false" >
   . . . . . . . .
   . . . . . . . .
   . . . . . . . .//Step definitions
</job>

Step

このタグは、SpringBatchジョブのステップを定義/構成するために使用されます。 次の3つの属性があります-

S.No Attribute & Description
1

Id

ジョブのIDです。この属性に値を指定することは必須です。

2

next

次のステップを指定するショートカットです。

3

parent

構成の継承元の親Beanの名前を指定するために使用されます。

以下は、SpringBatchのステップのXML構成です。

<job id = "jobid">
   <step id = "step1" next = "step2"/>
   <step id = "step2" next = "step3"/>
   <step id = "step3"/>
</job>

チャンク

このタグは、 tasklet のチャンクを定義/構成するために使用されます。 次の4つの属性があります-

S.No Attribute & Description
1

reader

アイテムリーダーBeanの名前を表します。 タイプ org.springframework.batch.item.ItemReader の値を受け入れます。

2

writer

アイテムリーダーBeanの名前を表します。 タイプ org.springframework.batch.item.ItemWriter の値を受け入れます。

3

processor

アイテムリーダーBeanの名前を表します。 タイプ org.springframework.batch.item.ItemProcessor の値を受け入れます。

4

commit-interval

トランザクションをコミットする前に処理されるアイテムの数を指定するために使用されます。

次に、SpringBatchのチャンクのXML構成を示します。

<batch:step id = "step1">
   <batch:tasklet>
      <batch:chunk reader = "xmlItemReader"
         writer = "mysqlItemWriter" processor = "itemProcessor" commit-interval = "10">
      </batch:chunk>
   </batch:tasklet>
</batch:step>

JobRepository

JobRepository Beanは、リレーショナルデータベースを使用してJobRepositoryを構成するために使用されます。 このBeanは、 org.springframework.batch.core.repository.JobRepository 型のクラスに関連付けられています。

S.No Attribute & Description
1

dataSource

データソースを定義するBean名の指定に使用されます。

2

transactionManager

transactionmanagerを定義するBeanの名前を指定するために使用されます。

3

databaseType

ジョブリポジトリで使用されるリレーショナルデータベースのタイプを指定します。

次に、JobRepositoryの構成例を示します。

<bean id = "jobRepository"
   class = "org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
   <property name = "dataSource" ref = "dataSource"/>
   <property name = "transactionManager" ref="transactionManager"/>
   <property name = "databaseType" value = "mysql"/>
</bean>

JobLauncher

JobLauncher Beanを使用して、JobLauncherを構成します。 これは、クラス org.springframework.batch.core.launch.support.SimpleJobLauncher (プログラム内)に関連付けられています。 このBeanには jobrepository という名前のプロパティが1つあり、 jobrepository を定義するBeanの名前を指定するために使用されます。

以下は、jobLauncherの構成例です。

<bean id = "jobLauncher"
   class = "org.springframework.batch.core.launch.support.SimpleJobLauncher">
   <property name = "jobRepository" ref = "jobRepository"/>
</bean>

TransactionManager

TransactionManager Beanは、リレーショナルデータベースを使用してTransactionManagerを構成するために使用されます。 このBeanは、 org.springframework.transaction.platform.TransactionManager タイプのクラスに関連付けられています。

<bean id = "transactionManager"
   class = "org.springframework.batch.support.transaction.ResourcelessTransactionManager"/>

情報源

データソースBeanは、データソース*の構成に使用されます。 このBeanは、 *org.springframework.jdbc.datasource.DriverManagerDataSource タイプのクラスに関連付けられています。

S.No Attribute & Description
1

driverClassName

これは、データベースとの接続に使用されるドライバーのクラス名を指定します。

2

url

これは、データベースのURLを指定します。

3

username

これは、データベースに接続するためのユーザー名を指定します。

4

password

これは、データベースに接続するためのパスワードを指定します。

以下は datasource の設定例です。

<bean id = "dataSource"
   class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
   <property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
   <property name = "url" value = "jdbc:mysql://localhost:3306/details"/>
   <property name = "username" value = "myuser"/>
   <property name = "password" value = "password"/>
</bean>

Spring Batch-リーダー、ライター、プロセッサー

  • アイテムリーダー*は特定のソースからスプリングバッチアプリケーションにデータを読み込み、*アイテムライター*はスプリングバッチアプリケーションから特定の宛先にデータを書き込みます。
  • アイテムプロセッサ*は、スプリングバッチに読み込まれたデータを処理する処理コードを含むクラスです。 アプリケーションがn個のレコードを読み取ると、プロセッサ内のコードが各レコードで実行されます。

チャンク*は *tasklet の子要素です。 読み取り、書き込み、および処理操作を実行するために使用されます。 以下に示すステップ内で、この要素を使用してリーダー、ライター、およびプロセッサーを構成できます。

<batch:job id = "helloWorldJob">
   <batch:step id = "step1">
      <batch:tasklet>
         <batch:chunk reader = "cvsFileItemReader" writer = "xmlItemWriter"
            processor = "itemProcessor" commit-interval = "10">
         </batch:chunk>
      </batch:tasklet>
   </batch:step>
</batch:job>

Spring Batchは、MongoDB、Neo4j、MySQL、XML、フラットファイル、CSVなどのさまざまなファイルシステム/データベースからデータを読み書きするリーダーとライターを提供します。

アプリケーションにリーダーを含めるには、そのリーダーのBeanを定義し、Bean内のすべての必須プロパティに値を提供し、そのようなBeanの id をチャンク要素 readerの属性に値として渡す必要があります。 (*作家*と同じ)。

ItemReader

データを読み取るのは、(バッチプロセスの)ステップのエンティティです。 ItemReaderは、一度に1つのアイテムを読み取ります。 Spring Batchはインターフェース ItemReader を提供します。 すべての*リーダー*がこのインターフェースを実装しています。

以下は、さまざまなソースから読み取るために、Spring Batchが提供する定義済みのItemReaderクラスの一部です。

Reader Purpose
FlatFIleItemReader To read data from flat files.
StaxEventItemReader To read data from XML files.
StoredProcedureItemReader To read data from the stored procedures of a database.
JDBCPagingItemReader To read data from relational databases database.
MongoItemReader To read data from MongoDB.
Neo4jItemReader To read data from Neo4jItemReader.

Beanを作成して ItemReaders を構成する必要があります。 以下は、XMLファイルからデータを読み取る StaxEventItemReader の例です。

<bean id = "mysqlItemWriter"
   class = "org.springframework.batch.item.xml.StaxEventItemWriter">
   <property name = "resource" value = "file:xml/outputs/userss.xml"/>
   <property name = "marshaller" ref = "reportMarshaller"/>
   <property name = "rootTagName" value = "Tutorial"/>
</bean>

<bean id = "reportMarshaller"
   class = "org.springframework.oxm.jaxb.Jaxb2Marshaller">
   <property name = "classesToBeBound">
      <list>
         <value>Tutorial</value>
      </list>
   </property>
</bean>

観察したように、構成中に、必要なリーダーのそれぞれのクラス名を指定する必要があり、すべての必要なプロパティに値を提供する必要があります。

ItemWriter

これは、データを書き込むバッチプロセスの step の要素です。 ItemWriterは、一度に1つのアイテムを書き込みます。 Spring Batchはインターフェース ItemWriter を提供します。 すべてのライターがこのインターフェイスを実装しています。

以下は、Spring Batchがさまざまなソースから読み取るために提供する事前定義済みItemWriterクラスの一部です。

Writer Purpose
FlatFIleItemWriter To write data into flat files.
StaxEventItemWriter To write data into XML files.
StoredProcedureItemWriter To write data into the stored procedures of a database.
JDBCPagingItemWriter To write data into relational databases database.
MongoItemWriter To write data into MongoDB.
Neo4jItemWriter To write data into Neo4j.

同様に、Beanを作成してItemWriterを構成する必要があります。 以下は、MySQLデータベースにデータを書き込む JdbcCursorItemReader の例です。

<bean id = "dbItemReader"
   class = "org.springframework.batch.item.database.JdbcCursorItemReader" scope = "step">
   <property name = "dataSource" ref = "dataSource"/>
   <property name = "sql" value = "select * from tutorialsdata"/>
   <property name = "rowMapper">
      <bean class = "TutorialRowMapper"/>
   </property>
</bean>

アイテムプロセッサー

*ItemProcessor* :ItemProcessorはデータの処理に使用されます。 指定されたアイテムが無効な場合は *null* を返し、そうでない場合は指定されたアイテムを処理して処理結果を返します。 インターフェイス *ItemProcessor <I、O>* はプロセッサを表します。
  • Taskletクラス*- reader および writer が指定されていない場合、TaskletはSpringBatchのプロセッサとして機能します。 単一のタスクのみを処理します。

パッケージ org.springframework.batch.item.ItemProcessor のインターフェイス ItemProcessor を実装することにより、カスタムアイテムプロセッサを定義できます。 このItemProcessorクラスはオブジェクトを受け入れ、データを処理し、処理されたデータを別のオブジェクトとして返します。

バッチプロセスでは、 "n" レコードまたはデータ要素が読み取られると、各レコードについて、データを読み取り、処理し、ライターにデータを書き込みます。 データを処理するには、渡されたプロセッサで中継します。

たとえば、特定のPDFドキュメントを読み込み、新しいページを作成し、データ形式を表形式でPDFに書き込むためのコードを記述したとします。 このアプリケーションを実行すると、XMLドキュメントからすべてのデータ項目が読み取られ、MySQLデータベースに保存され、個々のページの指定されたPDFドキュメントに印刷されます。

以下は、ItemProcessorクラスのサンプルです。

import org.springframework.batch.item.ItemProcessor;

public class CustomItemProcessor implements ItemProcessor<Tutorial, Tutorial> {

   @Override
   public Tutorial process(Tutorial item) throws Exception {
      System.out.println("Processing..." + item);
      return item;
   }
}

Spring Batch-基本アプリケーション

この章では、基本的なSpring Batchアプリケーションについて説明します。 tasklet を実行してメッセージを表示するだけです。

私たちのSpring Batchアプリケーションには、次のファイルが含まれています-

  • 構成ファイル-これは、ジョブとジョブのステップを定義するXMLファイルです。 (アプリケーションにリーダーとライターも含まれる場合、 readerswriters の構成もこのファイルに含まれます。)
  • Context.xml -このファイルでは、ジョブリポジトリ、ジョブランチャー、トランザクションマネージャーなどのBeanを定義します。
  • * Taskletクラス*-このクラスでは、処理コードジョブを記述します(この場合、簡単なメッセージを表示します)
  • * Launcherクラス*-このクラスでは、ジョブランチャーを実行してバッチアプリケーションを起動します。

jobConfig.xml

サンプルのSpring Batchアプリケーションの設定ファイルは次のとおりです。

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:batch = "http://www.springframework.org/schema/batch"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/batch
      http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd ">
   <import resource="context.xml"/>
   <!-- Defining a bean -->
   <bean id = "tasklet" class = "a_sample.MyTasklet"/>
   <!-- Defining a job-->
   <batch:job id = "helloWorldJob">
      <!-- Defining a Step -->
      <batch:step id = "step1">
         <tasklet ref = "tasklet"/>
      </batch:step>
   </batch:job>
</beans>

Context.xml

以下は、Spring Batchアプリケーションの context.xml です。

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

   <bean id = "jobRepository"
      class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean">
      <property name = "transactionManager" ref = "transactionManager"/>
   </bean>

   <bean id = "transactionManager"
      class = "org.springframework.batch.support.transaction.ResourcelessTransactionManager"/>
   <bean id = "jobLauncher"
      class = "org.springframework.batch.core.launch.support.SimpleJobLauncher">
      <property name = "jobRepository" ref = "jobRepository"/>
   </bean>
</beans>

Tasklet.java

以下は、簡単なメッセージを表示するTaskletクラスです。

import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;

public class MyTasklet implements Tasklet {

   @Override
   public RepeatStatus execute(StepContribution arg0, ChunkContext arg1) throws Exception {
      System.out.println("Hello This is a sample example of spring batch");
      return RepeatStatus.FINISHED;
   }
}

App.java

以下は、バッチ処理を実行するコードです。

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)throws Exception {

     //System.out.println("hello");
      String[] springConfig  =  {"a_sample/job_hello_world.xml"};

     //Creating the application context object
      ApplicationContext context = new ClassPathXmlApplicationContext(springConfig);

     //Creating the job launcher
      JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");

     //Creating the job
      Job job = (Job) context.getBean("helloWorldJob");

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

実行すると、上記のSpringBatchプログラムは次の出力を生成します-

Apr 24, 2017 4:40:54 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO:Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@2ef1e4fa: startup date [Mon Apr 24 16:40:54 IST 2017]; root of context hierarchy
Apr 24, 2017 4:40:54 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions INFO: Loading XML bean definitions
Apr 24, 2017 4:40:54 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions
Apr 24, 2017 4:40:54 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
Apr 24, 2017 4:40:55 PM org.springframework.batch.core.launch.support.SimpleJobLauncher afterPropertiesSet
INFO: No TaskExecutor has been set, defaulting to synchronous executor.
Apr 24, 2017 4:40:55 PM org.springframework.batch.core.launch.support.SimpleJobLauncher$1 run
INFO: Job: [FlowJob: [name=helloWorldJob]] launched with the following parameters: [{}]
Apr 24, 2017 4:40:55 PM org.springframework.batch.core.job.SimpleStepHandler handleStep INFO: Executing step: [step1]
Hello This is a sample example of spring batch
Apr 24, 2017 4:40:55 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

Spring Batch-XMLからMySQL

この章では、XMLリーダーとMySQLライターを使用するSpring Batchアプリケーションを作成します。

*Reader* -アプリケーションで使用しているリーダーは、XMLドキュメントからデータを読み取る *StaxEventItemReader* です。

以下は、このアプリケーションで使用している入力XMLドキュメントです。 このドキュメントには、チュートリアルID、チュートリアル作成者、チュートリアルタイトル、提出日、チュートリアルアイコン、チュートリアルの説明などの詳細を指定するデータレコードが含まれています。

<?xml version="1.0" encoding="UTF-8"?>
<tutorials>
   <tutorial>
      <tutorial_id>1001</tutorial_id>
      <tutorial_author>Sanjay</tutorial_author>
      <tutorial_title>Learn Java</tutorial_title>
      <submission_date>06-05-2007</submission_date>
      <tutorial_icon>https://www.finddevguides.com/java/images/java-minilogo.jpg</tutorial_icon>
      <tutorial_description>Java is a high-level programming language originally
         developed by Sun Microsystems and released in 1995.
         Java runs on a variety of platforms.
         This tutorial gives a complete understanding of Java.');</tutorial_description>
   </tutorial>

   <tutorial>
      <tutorial_id>1002</tutorial_id>
      <tutorial_author>Abdul S</tutorial_author>
      <tutorial_title>Learn MySQL</tutorial_title>
      <submission_date>19-04-2007</submission_date>
      <tutorial_icon>https://www.finddevguides.com/mysql/images/mysql-minilogo.jpg</tutorial_icon>
      <tutorial_description>MySQL is the most popular
         Open Source Relational SQL database management system.
         MySQL is one of the best RDBMS being used for developing web-based software applications.
         This tutorial will give you quick start with MySQL
         and make you comfortable with MySQL programming.</tutorial_description>
   </tutorial>

   <tutorial>
      <tutorial_id>1003</tutorial_id>
      <tutorial_author>Krishna Kasyap</tutorial_author>
      <tutorial_title>Learn JavaFX</tutorial_title>
      <submission_date>06-07-2017</submission_date>
      <tutorial_icon>https://www.finddevguides.com/javafx/images/javafx-minilogo.jpg</tutorial_icon>
      <tutorial_description>JavaFX is a Java library used to build Rich Internet Applications.
         The applications developed using JavaFX can run on various devices
         such as Desktop Computers, Mobile Phones, TVs, Tablets, etc.
         This tutorial, discusses all the necessary elements of JavaFX that are required
         to develop effective Rich Internet Applications</tutorial_description>
   </tutorial>
</tutorials>
*Writer* -アプリケーションで使用している *writer* は、MySQLデータベースにデータを書き込むための *JdbcBatchItemWriter* です。 *"details"* と呼ばれるデータベース内にMySQLのテーブルを作成したと仮定します。
CREATE TABLE details.TUTORIALS(
   tutorial_id int(10) NOT NULL,
   tutorial_author VARCHAR(20),
   tutorial_title VARCHAR(50),
   submission_date VARCHAR(20),
   tutorial_icon VARCHAR(200),
   tutorial_description VARCHAR(1000)
);

プロセッサ-アプリケーションで使用しているプロセッサは、PDFドキュメントに各レコードのデータを書き込むカスタムプロセッサです。

バッチ処理では、 "n" レコードまたはデータ要素が読み取られた場合、各レコードについて、データを読み取り、処理し、ライターにデータを書き込みます。 データを処理するには、渡されたプロセッサで中継します。 この場合、カスタムプロセッサクラスでは、特定のPDFドキュメントをロードし、新しいページを作成し、データ形式を表形式でPDFに書き込むコードを作成しました。

最後に、このアプリケーションを実行すると、XMLドキュメントからすべてのデータ項目が読み取られ、MySQLデータベースに保存され、特定のPDFドキュメントの個々のページに印刷されます。

jobConfig.xml

サンプルのSpring Batchアプリケーションの設定ファイルは次のとおりです。 このファイルでは、ジョブとステップを定義します。 これらに加えて、ItemReader、ItemProcessor、ItemWriterのBeanも定義します。 (ここでは、それらをそれぞれのクラスに関連付け、必要なプロパティの値を渡して設定します。)

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:batch = "http://www.springframework.org/schema/batch"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:util = "http://www.springframework.org/schema/util"
   xsi:schemaLocation = "http://www.springframework.org/schema/batch

      http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
      http://www.springframework.org/schema/util
      http://www.springframework.org/schema/util/spring-util-3.0.xsd ">

   <import resource = "../jobs/context.xml"/>

   <bean id = "itemProcessor" class = "CustomItemProcessor"/>
   <batch:job id = "helloWorldJob">
      <batch:step id = "step1">
         <batch:tasklet>
            <batch:chunk reader = "xmlItemReader" writer = "mysqlItemWriter" processor = "itemProcessor">
            </batch:chunk>
         </batch:tasklet>
      </batch:step>
   </batch:job>

   <bean id = "xmlItemReader"
      class = "org.springframework.batch.item.xml.StaxEventItemReader">
      <property name = "fragmentRootElementName" value = "tutorial"/>
      <property name = "resource" value = "classpath:resources/tutorial.xml"/>
      <property name = "unmarshaller" ref = "customUnMarshaller"/>
   </bean>

   <bean id = "customUnMarshaller" class = "org.springframework.oxm.xstream.XStreamMarshaller">
      <property name = "aliases">
         <util:map id = "aliases">
            <entry key = "tutorial" value = "Tutorial"/>
         </util:map>
      </property>
   </bean>
   <bean id = "mysqlItemWriter" class = "org.springframework.batch.item.database.JdbcBatchItemWriter">
      <property name = "dataSource" ref = "dataSource"/>
      <property name = "sql">
         <value>
            <![CDATA[insert into details.tutorials (tutorial_id, tutorial_author, tutorial_title,
               submission_date, tutorial_icon, tutorial_description)
               values (:tutorial_id, :tutorial_author, :tutorial_title, :submission_date,
               :tutorial_icon, :tutorial_description);]]>
         </value>
      </property>

      <property name = "itemSqlParameterSourceProvider">
         <bean class = "org.springframework.batch.item.database.BeanPropertyItemSqlParameterSourceProvider"/>
      </property>
   </bean>
</beans>

Context.xml

以下は、Spring Batchアプリケーションの context.xml です。 このファイルでは、ジョブリポジトリ、ジョブランチャー、トランザクションマネージャーなどのBeanを定義します。

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:jdbc = "http://www.springframework.org/schema/jdbc"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
      http://www.springframework.org/schema/jdbc
      http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd">

   <!-- stored job-meta in database -->
   <bean id = "jobRepository"
      class = "org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
      <property name = "dataSource" ref = "dataSource"/>
      <property name = "transactionManager" ref = "transactionManager"/>
      <property name = "databaseType" value = "mysql"/>
   </bean>

   <bean id = "transactionManager"
   class = "org.springframework.batch.support.transaction.ResourcelessTransactionMana ger"/>
   <bean id = "jobLauncher"
      class = "org.springframework.batch.core.launch.support.SimpleJobLauncher">
      <property name = "jobRepository" ref = "jobRepository"/>
   </bean>

   <!-- connect to MySQL database -->
   <bean id = "dataSource"
      class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
      <property name = "url" value = "jdbc:mysql://localhost:3306/details"/>
      <property name = "username" value = "myuser"/>
      <property name = "password" value = "password"/>
   </bean>

   <!-- create job-meta tables automatically -->
   <jdbc:initialize-database data-source = "dataSource">
      <jdbc:script location = "org/springframework/batch/core/schema-drop-mysql.sql"/>
      <jdbc:script location = "org/springframework/batch/core/schema-mysql.sql"/>
   </jdbc:initialize-database>
</beans>

CustomItemProcessor.java

以下は processor クラスです。 このクラスでは、アプリケーションで処理のコードを記述します。 ここでは、PDFドキュメントをロードし、新しいページを作成し、テーブルを作成し、各レコードに次の値を挿入しています:チュートリアルID、チュートリアル名、作成者、テーブル内の提出日。

import java.io.File;
import java.io.IOException;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.springframework.batch.item.ItemProcessor;

public class CustomItemProcessor implements ItemProcessor<Tutorial, Tutorial> {

   public static void drawTable(PDPage page, PDPageContentStream contentStream,
      float y, float margin, String[][] content) throws IOException {
      final int rows = content.length;
      final int cols = content[0].length;
      final float rowHeight = 50;
      final float tableWidth = page.getMediaBox().getWidth()-(2*margin);
      final float tableHeight = rowHeight * rows;
      final float colWidth = tableWidth/(float)cols;
      final float cellMargin=5f;

     //draw the rows
      float nexty = y ;
      for (int i = 0; i <= rows; i++) {
         contentStream.drawLine(margin,nexty,margin+tableWidth,nexty);
         nexty-= rowHeight;
      }

     //draw the columns
      float nextx = margin;
      for (int i = 0; i <= cols; i++) {
         contentStream.drawLine(nextx,y,nextx,y-tableHeight);
         nextx += colWidth;
      }

     //now add the text
      contentStream.setFont(PDType1Font.HELVETICA_BOLD,12);

      float textx = margin+cellMargin;
      float texty = y-15;
      for(int i = 0; i < content.length; i++){
         for(int j = 0 ; j < content[i].length; j++){
            String text = content[i][j];
            contentStream.beginText();
            contentStream.moveTextPositionByAmount(textx,texty);
            contentStream.drawString(text);
            contentStream.endText();
            textx += colWidth;
         }

         texty-=rowHeight;
         textx = margin+cellMargin;
      }
   }

   @Override
   public Tutorial process(Tutorial item) throws Exception {
      System.out.println("Processing..." + item);

     //Creating PDF document object
      PDDocument doc = PDDocument.load(new File("C:/Examples/test.pdf"));

     //Creating a blank page
      PDPage page = new PDPage();
      doc.addPage( page );
      PDPageContentStream contentStream =  new PDPageContentStream(doc, page);

      String[][] content = {{"Id",""+item.getTutorial_id()},
      {"Title", item.getTutorial_title()},
      {"Authour", item.getTutorial_author()},
      {"Submission Date", item.getSubmission_date()}} ;
      drawTable(page, contentStream, 700, 100, content);

      contentStream.close();
      doc.save("C:/Examples/test.pdf" );
      System.out.println("Hello");
      return item;
   }
}

TutorialFieldSetMapper.java

以下は、データをチュートリアルクラスに設定するReportFieldSetMapperクラスです。

import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.validation.BindException;

public class TutorialFieldSetMapper implements FieldSetMapper<Tutorial> {

   @Override
   public Tutorial mapFieldSet(FieldSet fieldSet) throws BindException {
     //instantiating the Tutorial class
      Tutorial tutorial = new Tutorial();

     //Setting the fields from XML
      tutorial.setTutorial_id(fieldSet.readInt(0));
      tutorial.setTutorial_title(fieldSet.readString(1));
      tutorial.setTutorial_author(fieldSet.readString(2));
      tutorial.setTutorial_icon(fieldSet.readString(3));
      tutorial.setTutorial_description(fieldSet.readString(4));
      return tutorial;
   }
}

Tutorial.java

以下は Tutorial クラスです。 これは、 setter および getter メソッドを持つ単純なクラスです。

public class Tutorial {
   private int tutorial_id;
   private String tutorial_author;
   private String tutorial_title;
   private String submission_date;
   private String tutorial_icon;
   private String tutorial_description;

   @Override
   public String toString() {
      return " [id=" + tutorial_id + ", author=" + tutorial_author
         + ", title=" + tutorial_title + ", date=" + submission_date + ", icon ="
         +tutorial_icon +", description = "+tutorial_description+"]";
   }

   public int getTutorial_id() {
      return tutorial_id;
   }

   public void setTutorial_id(int tutorial_id) {
      this.tutorial_id = tutorial_id;
   }

   public String getTutorial_author() {
      return tutorial_author;
   }

   public void setTutorial_author(String tutorial_author) {
      this.tutorial_author = tutorial_author;
   }

   public String getTutorial_title() {
      return tutorial_title;
   }

   public void setTutorial_title(String tutorial_title) {
      this.tutorial_title = tutorial_title;
   }

   public String getSubmission_date() {
      return submission_date;
   }

   public void setSubmission_date(String submission_date) {
      this.submission_date = submission_date;
   }

   public String getTutorial_icon() {
      return tutorial_icon;
   }

   public void setTutorial_icon(String tutorial_icon) {
      this.tutorial_icon = tutorial_icon;
   }

   public String getTutorial_description() {
      return tutorial_description;
   }

   public void setTutorial_description(String tutorial_description) {
      this.tutorial_description = tutorial_description;
   }
}

App.java

以下は、バッチ処理を実行するコードです。 このクラスでは、JobLauncherを実行してバッチアプリケーションを起動します。

public class App {
   public static void main(String[] args) throws Exception {
      String[] springConfig  = {    "jobs/job_hello_world.xml" };

     //Creating the application context object
      ApplicationContext context = new ClassPathXmlApplicationContext(springConfig);

     //Creating the job launcher
      JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");

     //Creating the job
      Job job = (Job) context.getBean("helloWorldJob");

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

このアプリケーションを実行すると、次の出力が生成されます。

May 05, 2017 4:39:22 PM org.springframework.context.support.ClassPathXmlApplicationContext
prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@306a30c7:
startup date [Fri May 05 16:39:22 IST 2017]; root of context hierarchy
May 05, 2017 4:39:23 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
May 05, 2017 4:39:32 PM org.springframework.batch.core.job.SimpleStepHandler handleStep
INFO: Executing step: [step1]
Processing... [id=1001, author=Sanjay, title=Learn Java, date=06-05-2007,
icon =https://www.finddevguides.com/java/images/java-mini-logo.jpg,
description = Java is a high-level programming language originally developed by Sun Microsystems
and released in 1995. Java runs on a variety of platforms.
This tutorial gives a complete understanding of Java.');]
Hello
Processing.. [id=1002, author=Abdul S, title=Learn MySQL, date=19-04-2007,
icon =https://www.finddevguides.com/mysql/images/mysql-mini-logo.jpg,
description = MySQL is the most popular Open Source Relational SQL database management system.
MySQL is one of the best RDBMS being used for developing web-based software applications.
This tutorial will give you quick start with MySQL and make you comfortable with MySQL programming.]
Hello
Processing... [id=1003, author=Krishna Kasyap, title=Learn JavaFX, date=06-072017,
icon =https://www.finddevguides.com/javafx/images/javafx-mini-logo.jpg,
description = JavaFX is a Java library used to build Rich Internet Applications.
The applications developed using JavaFX can run on various devices
such as Desktop Computers, Mobile Phones, TVs, Tablets, etc.
This tutorial, discusses all the necessary elements of JavaFX
that are required to develop effective Rich Internet Applications]
Hello
May 05, 2017 4:39:36 PM org.springframework.batch.core.launch.support.SimpleJobLauncher run
INFO: Job: [FlowJob: [name=helloWorldJob]] completed with the following parameters: [{}]
and the following status: [COMPLETED]
Exit Status : COMPLETED

データベースの details.tutorial テーブルを確認すると、次の出力が表示されます-

tutorial _id tutorial _author tutorial _title submission _date tutorial _icon tutorial _description
1001 Sanjay Learn Java 06-05-2007 https://www.tutorials point.com/java/images/java-mini-logo.jpg Java is a high-level programming language originally developed by Sun Microsystems and released in 1995. Java runs on a variety of platforms. This tutorial gives a complete understanding of Java.
1002 Abdul S Learn MySQL 19-04-2007 https://www. finddevguides.com/mysql/images/mysql-minilogo.jpg MySQL is the most popular Open Source Relational SQL database management system. MySQL is one of the best RDBMS being used for developing web-based software applications. This tutorial will give you quick start with MySQL and make you comfortable with MySQL programming.
1003 Learn JavaFX Krishna Kasyap 06-07-2017 https://www. finddevguides.com/javafx/images/javafx-minilogo.jpg MySQL is the most popular Open Source Relational SQL database management system. MySQL is one of the best RDBMS being used for developing web-based software applications. This tutorial will give you quick start with MySQL and make you comfortable with MySQL programming.

これにより、以下に示すように各ページのレコードを含むPDFが生成されます。

ページサムネイル

Spring Batch-CSVからXML

この章では、CSVリーダーとXMLライターを使用する簡単なSpring Batchアプリケーションを作成します。

*Reader* -アプリケーションで使用している *reader* は、CSVファイルからデータを読み取る *FlatFileItemReader* です。

以下は、このアプリケーションで使用している入力CSVファイルです。 このドキュメントには、チュートリアルID、チュートリアル作成者、チュートリアルタイトル、提出日、チュートリアルアイコン、チュートリアルの説明などの詳細を指定するデータレコードが含まれています。

1001, "Sanjay", "Learn Java", 06/05/2007
1002, "Abdul S", "Learn MySQL", 19/04/2007
1003, "Krishna Kasyap", "Learn JavaFX", 06/07/2017
*Writer* -アプリケーションで使用しているWriterは、データをXMLファイルに書き込む *StaxEventItemWriter* です。

プロセッサ-アプリケーションで使用しているプロセッサは、CSVファイルから読み取ったレコードを印刷するだけのカスタムプロセッサです。

jobConfig.xml

サンプルのSpring Batchアプリケーションの設定ファイルは次のとおりです。 このファイルでは、ジョブとステップを定義します。 これらに加えて、ItemReader、ItemProcessor、ItemWriterのBeanも定義します。 (ここでは、それらをそれぞれのクラスに関連付け、必要なプロパティの値を渡して設定します。)

<beans xmlns = " http://www.springframework.org/schema/beans"
   xmlns:batch = "http://www.springframework.org/schema/batch"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/batch
      http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

   <import resource = "../jobs/context.xml"/>

   <bean id = "report" class = "Report" scope = "prototype"/>
   <bean id = "itemProcessor" class = "CustomItemProcessor"/>

   <batch:job id = "helloWorldJob">

      <batch:step id = "step1">

         <batch:tasklet>
            <batch:chunk reader = "cvsFileItemReader" writer = "xmlItemWriter"
               processor = "itemProcessor" commit-interval = "10">
            </batch:chunk>
         </batch:tasklet>
      </batch:step>
   </batch:job>

   <bean id = "cvsFileItemReader"
      class = "org.springframework.batch.item.file.FlatFileItemReader">
      <property name = "resource" value = "classpath:resources/report.csv"/>
      <property name = "lineMapper">
         <bean
            class = "org.springframework.batch.item.file.mapping.DefaultLineMapper">
            <property name = "lineTokenizer">
               <bean
                  class = "org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
                  <property name = "names" value = "tutorial_id,
                     tutorial_author, Tutorial_title, submission_date"/>
               </bean>
            </property>

            <property name = "fieldSetMapper">
               <bean class = "ReportFieldSetMapper"/>
            </property>
         </bean>
      </property>
   </bean>

   <bean id = "xmlItemWriter"
      class = "org.springframework.batch.item.xml.StaxEventItemWriter">
      <property name = "resource" value = "file:xml/outputs/tutorials.xml"/>
      <property name = "marshaller" ref = "reportMarshaller"/>
      <property name = "rootTagName" value = "tutorials"/>
   </bean>

   <bean id = "reportMarshaller"
      class = "org.springframework.oxm.jaxb.Jaxb2Marshaller">
      <property name = "classesToBeBound">
         <list>
            <value>Tutorial</value>
         </list>
      </property>
   </bean>
</beans>

Context.xml

以下は、Spring Batchアプリケーションの context.xml です。 このファイルでは、ジョブリポジトリ、ジョブランチャー、トランザクションマネージャーなどのBeanを定義します。

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:jdbc = "http://www.springframework.org/schema/jdbc"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
      http://www.springframework.org/schema/jdbc
      http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd">
   <!-- stored job-meta in database -->
   <bean id = "jobRepository"
      class = "org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
      <property name = "dataSource" ref = "dataSource"/>
      <property name = "transactionManager" ref = "transactionManager"/>
      <property name = "databaseType" value = "mysql"/>
   </bean>

   <bean id = "transactionManager"
      class = "org.springframework.batch.support.transaction.ResourcelessTransactionManager"/>
   <bean id = "jobLauncher"
      class = "org.springframework.batch.core.launch.support.SimpleJobLauncher">
      <property name = "jobRepository" ref = "jobRepository"/>
   </bean>

   <bean id = "dataSource" class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
      <property name = "url" value = "jdbc:mysql://localhost:3306/details"/>
      <property name = "username" value = "myuser"/>
      <property name = "password" value = "password"/>
   </bean>

   <!-- create job-meta tables automatically -->
   <jdbc:initialize-database data-source = "dataSource">
      <jdbc:script location = "org/springframework/batch/core/schema-drop-mysql.sql"/>
      <jdbc:script location = "org/springframework/batch/core/schema-mysql.sql"/>
   </jdbc:initialize-database>
</beans>

CustomItemProcessor.java

プロセッサクラスは次のとおりです。 このクラスでは、アプリケーションで処理のコードを記述します。 ここでは、各レコードの内容を印刷しています。

import org.springframework.batch.item.ItemProcessor;

public class CustomItemProcessor implements ItemProcessor<Tutorial, Tutorial> {

   @Override
   public Tutorial process(Tutorial item) throws Exception {
      System.out.println("Processing..." + item);
      return item;
   }
}

TutorialFieldSetMapper.java

以下は、データをTutorialクラスに設定するTutorialFieldSetMapperクラスです。

import org.springframework.batch.item.file.mapping.FieldSetMapper;
import org.springframework.batch.item.file.transform.FieldSet;
import org.springframework.validation.BindException;

public class TutorialFieldSetMapper implements FieldSetMapper<Tutorial> {

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

     //Instantiating the report object
      Tutorial tutorial = new Tutorial();

     //Setting the fields
      tutorial.setTutorial_id(fieldSet.readInt(0));
      tutorial.setTutorial_author(fieldSet.readString(1));
      tutorial.setTutorial_title(fieldSet.readString(2));
      tutorial.setSubmission_date(fieldSet.readString(3));

      return tutorial;
   }
}

Tutorial.javaクラス

以下は Tutorial クラスです。 これは、 setter および getter メソッドを持つ単純なJavaクラスです。 このクラスでは、アノテーションを使用して、このクラスのメソッドをXMLファイルのタグに関連付けています。

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "tutorial")
public class Tutorial {
   private int tutorial_id;
   private String tutorial_author;
   private String tutorial_title;
   private String submission_date;

   @XmlAttribute(name = "tutorial_id")
   public int getTutorial_id() {
      return tutorial_id;
   }

   public void setTutorial_id(int tutorial_id) {
      this.tutorial_id = tutorial_id;
   }

   @XmlElement(name = "tutorial_author")
   public String getTutorial_author() {
      return tutorial_author;
   }
   public void setTutorial_author(String tutorial_author) {
      this.tutorial_author = tutorial_author;
   }

   @XmlElement(name = "tutorial_title")
   public String getTutorial_title() {
      return tutorial_title;
   }

   public void setTutorial_title(String tutorial_title) {
      this.tutorial_title = tutorial_title;
   }

   @XmlElement(name = "submission_date")
   public String getSubmission_date() {
      return submission_date;
   }

   public void setSubmission_date(String submission_date) {
      this.submission_date = submission_date;
   }

   @Override
   public String toString() {
      return "  [Tutorial id=" + tutorial_id + ",
         Tutorial Author=" + tutorial_author  + ",
         Tutorial Title=" + tutorial_title + ",
         Submission Date=" + submission_date + "]";
   }
}

App.java

以下は、バッチプロセスを起動するコードです。 このクラスでは、JobLauncherを実行してバッチアプリケーションを起動します。

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) throws Exception {

      String[] springConfig  =  { "jobs/job_hello_world.xml" };

     //Creating the application context object
      ApplicationContext context = new ClassPathXmlApplicationContext(springConfig);

     //Creating the job launcher
      JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");

     //Creating the job
      Job job = (Job) context.getBean("helloWorldJob");

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

このアプリケーションを実行すると、次の出力が生成されます。

May 08, 2017 10:10:12 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing
org.springframework.context.support.ClassPathXmlApplicationContext@3d646c37: startup date
[Mon May 08 10:10:12 IST 2017]; root of context hierarchy
May 08, 2017 10:10:12 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
May 08, 2017 10:10:15 AM org.springframework.jdbc.datasource.init.ScriptUtils executeSqlScript
INFO: Executing step: [step1]
Processing...  [Tutorial id=1001, Tutorial Author=Sanjay,
Tutorial Title=Learn Java, Submission Date=06/05/2007]
Processing...  [Tutorial id=1002, Tutorial Author=Abdul S,
Tutorial Title=Learn MySQL, Submission Date=19/04/2007]
Processing...  [Tutorial id=1003, Tutorial Author=Krishna Kasyap,
Tutorial Title=Learn JavaFX, Submission Date=06/07/2017]
May 08, 2017 10:10:21 AM org.springframework.batch.core.launch.support.SimpleJobLauncher run
INFO: Job: [FlowJob: [name=helloWorldJob]] completed with the following parameters:
[{}] and the following status: [COMPLETED]
Exit Status : COMPLETED

これにより、次の内容のXMLファイルが生成されます。

<?xml version = "1.0" encoding = "UTF-8"?>
<tutorials>
   <tutorial tutorial_id = "1001">
      <submission_date>06/05/2007</submission_date>
      <tutorial_author>Sanjay</tutorial_author>
      <tutorial_title>Learn Java</tutorial_title>
   </tutorial>

   <tutorial tutorial_id = "1002">
      <submission_date>19/04/2007</submission_date>
      <tutorial_author>Abdul S</tutorial_author>
      <tutorial_title>Learn MySQL</tutorial_title>
   </tutorial>

   <tutorial tutorial_id = "1003">
      <submission_date>06/07/2017</submission_date>
      <tutorial_author>Krishna Kasyap</tutorial_author>
      <tutorial_title>Learn JavaFX</tutorial_title>
   </tutorial>
</tutorials>

Spring Batch-MySQLからXML

この章では、MySQLリーダーとXMLライターを使用するSpring Batchアプリケーションを作成します。

*Reader* -アプリケーションで使用しているリーダーは *JdbcCursorItemReader* で、MySQLデータベースからデータを読み取ります。

以下に示すように、MySQLデータベースにテーブルを作成したとします-

CREATE TABLE details.xml_mysql(
   person_id int(10) NOT NULL,
   sales VARCHAR(20),
   qty int(3),
   staffName VARCHAR(20),
   date VARCHAR(20)
);

次のレコードを挿入したとします。

mysql> select * from tutorialsdata;
+-------------+-----------------+----------------+-----------------+
| tutorial_id | tutorial_author | tutorial_title | submission_date |
+-------------+-----------------+----------------+-----------------+
|         101 | Sanjay          | Learn Java     | 06-05-2007      |
|         102 | Abdul S         | Learn MySQL    | 19-04-2007      |
|         103 | Krishna Kasyap  | Learn JavaFX   | 06-07-2017      |
+-------------+-----------------+----------------+-----------------+
3 rows in set (0.00 sec)
*Writer* -アプリケーションで使用しているWriterは、データをXMLファイルに書き込む *StaxEventItemWriter* です。

プロセッサ-アプリケーションで使用しているプロセッサは、CSVファイルから読み取ったレコードを印刷するだけのカスタムプロセッサです。

jobConfig.xml

サンプルのSpring Batchアプリケーションの設定ファイルは次のとおりです。 このファイルでは、ジョブとステップを定義します。 これらに加えて、ItemReader、ItemProcessor、ItemWriterのBeanも定義します。 (ここでは、それらをそれぞれのクラスに関連付け、必要なプロパティの値を渡して設定します。)

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:batch = "http://www.springframework.org/schema/batch"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:util = "http://www.springframework.org/schema/util"
   xsi:schemaLocation = " http://www.springframework.org/schema/batch
      http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

   <import resource = "../jobs/context.xml"/>

   <bean id = "report" class = "Report" scope = "prototype"/>
   <bean id = "itemProcessor" class = "CustomItemProcessor"/>

   <batch:job id = "helloWorldJob">
      <batch:step id = "step1">
         <batch:tasklet>
            <batch:chunk reader = "dbItemReader"
               writer = "mysqlItemWriter" processor = "itemProcessor" commit-interval = "10">
            </batch:chunk>
         </batch:tasklet>
      </batch:step>
   </batch:job>

   <bean id = "dbItemReader"
      class = "org.springframework.batch.item.database.JdbcCursorItemReader" scope = "step">
      <property name = "dataSource" ref = "dataSource"/>
      <property name = "sql" value = "select * from tutorials_data"/>
      <property name = "rowMapper">
         <bean class = "TutorialRowMapper"/>
      </property>
   </bean>
   <bean id = "mysqlItemWriter"
      class = "org.springframework.batch.item.xml.StaxEventItemWriter">
      <property name = "resource" value = "file:xml/outputs/tutorials.xml"/>
      <property name = "marshaller" ref = "reportMarshaller"/>
      <property name = "rootTagName" value = "Tutorial"/>
   </bean>

   <bean id = "reportMarshaller" class = "org.springframework.oxm.jaxb.Jaxb2Marshaller">
      <property name = "classesToBeBound">
         <list>
            <value>Tutorial</value>
         </list>
      </property>
   </bean>
</beans>

Context.xml

以下は、Spring Batchアプリケーションの context.xml です。 このファイルでは、ジョブリポジトリ、ジョブランチャー、トランザクションマネージャーなどのBeanを定義します。

<beans xmlns = " http://www.springframework.org/schema/beans"
   xmlns:jdbc = "http://www.springframework.org/schema/jdbc"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
      http://www.springframework.org/schema/jdbc
      http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd ">

   <!-- stored job-meta in database -->
   <bean id = "jobRepository"
      class = "org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
      <property name = "dataSource" ref = "dataSource"/>
      <property name = "transactionManager" ref = "transactionManager"/>
      <property name = "databaseType" value = "mysql"/>
   </bean>

   <bean id = "transactionManager"
      class = "org.springframework.batch.support.transaction.ResourcelessTransactionMana ger"/>
   <bean id = "jobLauncher"
      class = "org.springframework.batch.core.launch.support.SimpleJobLauncher">
      <property name = "jobRepository" ref = "jobRepository"/>
   </bean>

   <!-- connect to MySQL database -->
   <bean id = "dataSource"
      class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
      <property name = "url" value = "jdbc:mysql://localhost:3306/details"/>
      <property name = "username" value = "myuser"/>
      <property name = "password" value = "password"/>
   </bean>

   <!-- create job-meta tables automatically -->
   <jdbc:initialize-database data-source = "dataSource">
      <jdbc:script location = "org/springframework/batch/core/schema-drop-mysql.sql"/>
      <jdbc:script location = "org/springframework/batch/core/schema-mysql.sql"/>
   </jdbc:initialize-database>
</beans>

CustomItemProcessor.java

プロセッサクラスは次のとおりです。 このクラスでは、アプリケーションで処理のコードを記述します。 ここでは、各レコードの内容を印刷しています。

import org.springframework.batch.item.ItemProcessor;

public class CustomItemProcessor implements ItemProcessor<Tutorial, Tutorial> {

   @Override
   public Tutorial process(Tutorial item) throws Exception {
      System.out.println("Processing..." + item);
      return item;
   }
}

TutorialRowMapper.java

以下は、データを Tutorial クラスに設定する TutorialRowMapper クラスです。

import java.sql.ResultSet;
import java.sql.SQLException;
import org.springframework.jdbc.core.RowMapper;

public class TutorialRowMapper implements RowMapper<Tutorial> {

   @Override
   public Tutorial mapRow(ResultSet rs, int rowNum) throws SQLException {

      Tutorial tutorial = new Tutorial();
      tutorial.setTutorial_id(rs.getInt("tutorial_id"));
      tutorial.setTutorial_author(rs.getString("tutorial_author"));
      tutorial.setTutorial_title(rs.getString("tutorial_title"));
      tutorial.setSubmission_date(rs.getString("submission_date"));
      return tutorial;
   }
}

Tutorial.java

以下は Tutorial クラスです。 これは、 setter および getter メソッドを持つ単純なJavaクラスです。 このクラスでは、アノテーションを使用して、このクラスのメソッドをXMLファイルのタグに関連付けています。

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement(name = "details")
public class Tutorial {

   int tutorial_id;
   String tutorial_author;
   String submission_date;

   @XmlAttribute(name = "tutorial_id")
   public int getTutorial_id() {
      return tutorial_id;
   }

   public void setTutorial_id(int tutorial_id) {
      this.tutorial_id = tutorial_id;
   }

   @XmlElement(name = "tutorial_author")
   public String getTutorial_author() {
      return tutorial_author;
   }

   public void setTutorial_author(String tutorial_author) {
      this.tutorial_author = tutorial_author;
   }

   @XmlElement(name = "tutorial_title")
   public String getTutorial_title() {
      return tutorial_title;
   }

   public void setTutorial_title(String tutorial_title) {
      this.tutorial_title = tutorial_title;
   }

   @XmlElement(name = "submission_date")
   public String getSubmission_date() {
      return submission_date;
   }

   public void setSubmission_date(String submission_date) {
      this.submission_date = submission_date;
   }

   public String toString() {
      return " [Tutorial Id=" + tutorial_id + ",
      Tutorial Author =" + tutorial_author  + ",
      Tutorial Title =" + tutorial_title + ",
      Submission Date =" + submission_date + "]";
   }
}

App.java

以下は、バッチ処理を実行するコードです。 このクラスでは、JobLauncherを実行してバッチアプリケーションを起動します。

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) throws Exception {

      String[] springConfig  =  { "jobs/job_hello_world.xml" };

     //Creating the application context object
      ApplicationContext context = new ClassPathXmlApplicationContext(springConfig);

     //Creating the job launcher
      JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");

     //Creating the job
      Job job = (Job) context.getBean("helloWorldJob");

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

このアプリケーションを実行すると、次の出力が生成されます。

May 08, 2017 11:32:06 AM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@3d646c37:
startup date [Mon May 08 11:32:06 IST 2017]; root of context hierarchy
May 08, 2017 11:32:06 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [jobs/job_hello_world.xml]
May 08, 2017 11:32:07 AM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
May 08, 2017 11:32:14 AM org.springframework.batch.core.job.SimpleStepHandler handleStep
INFO: Executing step: [step1]
Processing... [Tutorial Id=101, Tutorial Author=Sanjay,
Tutorial Title=Learn Java, Submission Date=06-05-2007]
Processing... [Tutorial Id=102, Tutorial Author=Abdul S,
Tutorial Title=Learn MySQL, Submission Date=19-04-2007]
Processing... [Tutorial Id=103, Tutorial Author=Krishna Kasyap,
Tutorial Title=Learn JavaFX, Submission Date=06-07-2017]
May 08, 2017 11:32:14 AM org.springframework.batch.core.launch.support.SimpleJobLauncher run
INFO: Job: [FlowJob: [name=helloWorldJob]] completed with the following parameters:
[{}] and the following status: [COMPLETED]
Exit Status : COMPLETED

これにより、次の内容のXMLファイルが生成されます。

<?xml version = "1.0" encoding = "UTF-8"?>
<Tutorial>
   <details tutorial_id = "101">
      <submission_date>06-05-2007</submission_date>
      <tutorial_author>Sanjay</tutorial_author>
      <tutorial_title>Learn Java</tutorial_title>
   </details>

   <details tutorial_id = "102">
      <submission_date>19-04-2007</submission_date>
      <tutorial_author>Abdul S</tutorial_author>
      <tutorial_title>Learn MySQL</tutorial_title>
   </details>

   <details tutorial_id = "103">
      <submission_date>06-07-2017</submission_date>
      <tutorial_author>Krishna Kasyap</tutorial_author>
      <tutorial_title>Learn JavaFX</tutorial_title>
   </details>
</Tutorial>

Spring Batch-MySQLからフラットファイル

この章では、MySQL Readerと Flatfile Writer(.txt)を使用するSpring Batchアプリケーションを作成します。

*Reader* -アプリケーションで使用しているReaderは、MySQLデータベースからデータを読み取る *JdbcCursorItemReader* です。

以下に示すように、MySQLデータベースにテーブルを作成したと仮定します。

CREATE TABLE details.xml_mysql(
   person_id int(10) NOT NULL,
   sales VARCHAR(20),
   qty int(3),
   staffName VARCHAR(20),
   date VARCHAR(20)
);

次のレコードを挿入したとします。

mysql> select * from tutorialsdata;
+-------------+-----------------+----------------+-----------------+
| tutorial_id | tutorial_author | tutorial_title | submission_date |
+-------------+-----------------+----------------+-----------------+
|         101 | Sanjay          | Learn Java     | 06-05-2007      |
|         102 | Abdul S         | Learn MySQL    | 19-04-2007      |
|         103 | Krishna Kasyap  | Learn JavaFX   | 06-07-2017      |
+-------------+-----------------+----------------+-----------------+
3 rows in set (0.00 sec)
*Writer* -アプリケーションで使用しているWriterは、 *FlatFileItemWriter* で、データを *flatfile* (.txt)に書き込みます。

プロセッサ-アプリケーションで使用しているプロセッサは、CSVファイルから読み取ったレコードを印刷するだけのカスタムプロセッサです。

jobConfig.xml

サンプルのSpring Batchアプリケーションの設定ファイルは次のとおりです。 このファイルでは、ジョブとステップを定義します。 これらに加えて、ItemReader、ItemProcessor、ItemWriterのBeanも定義します。 (ここでは、それらをそれぞれのクラスに関連付け、必要なプロパティの値を渡して設定します。)

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:batch = "http://www.springframework.org/schema/batch"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:util = "http://www.springframework.org/schema/util"
   xsi:schemaLocation = "http://www.springframework.org/schema/batch

      http://www.springframework.org/schema/batch/spring-batch-2.2.xsd
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

   <import resource = "../jobs/context.xml"/>
   <bean id = "tutorial" class = "Tutorial" scope = "prototype"/>
   <bean id = "itemProcessor" class = "CustomItemProcessor"/>

   <batch:job id = "helloWorldJob">
      <batch:step id = "step1">
         <batch:tasklet>
            <batch:chunk reader = "mysqlItemReader"
               writer = "flatFileItemWriter" processor = "itemProcessor"
               commit-interval = "10">
            </batch:chunk>
         </batch:tasklet>
      </batch:step>
   </batch:job>

   <bean id = "mysqlItemReader"
      class = "org.springframework.batch.item.database.JdbcCursorItemReader" >
      <property name = "dataSource" ref = "dataSource"/>
      <property name = "sql" value = "select * from details.tutorialsdata"/>
      <property name = "rowMapper">
         <bean class = "TutorialRowMapper"/>
      </property>
   </bean>

   <bean id = "flatFileItemWriter"
      class = " org.springframework.batch.item.file.FlatFileItemWriter">
      <property name = "resource" value = "file:target/outputfiles/employee_output.txt"/>
      <property name = "lineAggregator">
         <bean class = " org.springframework.batch.item.file.transform.PassThroughLineAggregator"/>
      </property>
   </bean>
</beans>

Context.xml

以下は、Spring Batchアプリケーションの context.xml です。 このファイルでは、ジョブリポジトリ、ジョブランチャー、トランザクションマネージャーなどのBeanを定義します。

<beans xmlns = "http://www.springframework.org/schema/beans"
   xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
   xmlns:jdbc = "http://www.springframework.org/schema/jdbc"
   xsi:schemaLocation = "http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
      http://www.springframework.org/schema/jdbc
      http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd ">

   <!-- stored job-meta in database -->
   <bean id = "jobRepository"
      class = "org.springframework.batch.core.repository.support.JobRepositoryFactoryBean">
      <property name = "dataSource" ref = "dataSource"/>
      <property name = "transactionManager" ref = "transactionManager"/>
      <property name = "databaseType" value = "mysql"/>
   </bean>

   <bean id = "transactionManager"
      class = "org.springframework.batch.support.transaction.ResourcelessTransactionManager"/>

   <bean id = "dataSource"
      class = "org.springframework.jdbc.datasource.DriverManagerDataSource">
      <property name = "driverClassName" value = "com.mysql.jdbc.Driver"/>
      <property name = "url" value = "jdbc:mysql://localhost:3306/details"/>
      <property name = "username" value = "myuser"/>
      <property name = "password" value = "password"/>
   </bean>

   <bean id = "jobLauncher"
      class = "org.springframework.batch.core.launch.support.SimpleJobLauncher">
      <property name = "jobRepository" ref = "jobRepository"/>
   </bean>

   <!-- create job-meta tables automatically -->
   <jdbc:initialize-database data-source = "dataSource">
      <jdbc:script location = "org/springframework/batch/core/schema-drop-mysql.sql"/>
      <jdbc:script location = "org/springframework/batch/core/schema-mysql.sql"/>
   </jdbc:initialize-database>
</beans>

CustomItemProcessor.java

プロセッサクラスは次のとおりです。 このクラスでは、アプリケーションで処理のコードを記述します。 ここでは、各レコードの内容を印刷しています。

import org.springframework.batch.item.ItemProcessor;

//Implementing the ItemProcessor interface
public class CustomItemProcessor implements ItemProcessor<Tutorial, Tutorial> {

   @Override
   public Tutorial process(Tutorial item) throws Exception {
      System.out.println("Processing..." + item);
      return item;
   }
}

TutorialRowMapper.java

以下は、データを Tutorial クラスに設定する TutorialRowMapper クラスです。

public class TutorialRowMapper implements RowMapper<Tutorial> {

   @Override
   public Tutorial mapRow(ResultSet rs, int rowNum) throws SQLException {

      Tutorial tutorial = new Tutorial();

      tutorial.setTutorial_id(rs.getInt("tutorial_id"));
      tutorial.setTutorial_title(rs.getString("tutorial_title"));
      tutorial.setTutorial_author(rs.getString("tutorial_author"));
      tutorial.setSubmission_date(rs.getString("submission_date"));
      return tutorial;
   }
}

Tutorial.java

以下は Tutorial クラスです。 これは、 setter および getter メソッドを持つ単純なJavaクラスです。 このクラスでは、アノテーションを使用して、このクラスのメソッドをXMLファイルのタグに関連付けています。

public class Tutorial {
   private int tutorial_id;
   private String tutorial_title;
   private String tutorial_author;
   private String submission_date;

   public int getTutorial_id() {
      return tutorial_id;
   }

   public void setTutorial_id(int tutorial_id) {
      this.tutorial_id = tutorial_id;
   }

   public String getTutorial_title() {
      return tutorial_title;
   }

   public void setTutorial_title(String tutorial_title) {
      this.tutorial_title = tutorial_title;
   }

   public String getTutorial_author() {
      return tutorial_author;
   }

   public void setTutorial_author(String tutorial_author) {
      this.tutorial_author = tutorial_author;
   }

   public String getSubmission_date() {
      return submission_date;
   }
   public void setSubmission_date(String submission_date) {
      this.submission_date = submission_date;
   }

   @Override
   public String toString() {
      return " [id=" + tutorial_id + ", title=" +
      tutorial_title                      + ",
      author=" + tutorial_author + ", date=" +
      submission_date + "]";
   }
}

App.java

以下は、バッチ処理を実行するコードです。 このクラスでは、JobLauncherを実行してバッチアプリケーションを起動します。

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) throws Exception {

      String[] springConfig  =  { "jobs/job_hello_world.xml" };

     //Creating the application context object
      ApplicationContext context = new ClassPathXmlApplicationContext(springConfig);

     //Creating the job launcher
      JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");

     //Creating the job
      Job job = (Job) context.getBean("helloWorldJob");

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

このアプリケーションを実行すると、次の出力が生成されます。

May 09, 2017 5:44:48 PM org.springframework.context.support.ClassPathXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXml
ApplicationContext@3d646c37: startup date [Tue May
09 17:44:48 IST 2017]; root of context hierarchy
May 09, 2017 5:44:48 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
May 09, 2017 5:44:56 PM org.springframework.batch.core.launch.support.SimpleJobLauncher run
INFO: Job: [FlowJob: [name=helloWorldJob]] launched
with the following parameters: [{}]
May 09, 2017 5:44:56 PM org.springframework.batch.core.job.SimpleStepHandler handleStep
INFO: Executing step: [step1]
Processing...Report [id=101, title=Learn Java, author=Sanjay, date=06-05-2007]
Processing...Report [id=102, title=Learn MySQL, author=Abdul S, date=19-04-2007]
Processing...Report [id=103, title=Learn JavaFX, author=Krishna Kasyap, date=0607-2017]
May 09, 2017 5:44:57 PM org.springframework.batch.core.launch.support.SimpleJobLauncher run
INFO: Job: [FlowJob: [name=helloWorldJob]] completed with the following parameters:
[{}] and the following status: [COMPLETED]
Hello
Exit Status : COMPLETED

これにより、次の内容の .txt ファイルが生成されます。

Report [id=101, title=Learn Java, author=Sanjay, date=06-05-2007]
Report [id=102, title=Learn MySQL, author=Abdul S, date=19-04-2007]
Report [id=103, title=Learn JavaFX, author=Krishna Kasyap, date=06-07-2017]