Java Reference
In-Depth Information
9-5. Writing a Custom ItemWriter and ItemReader
Problem
You want to talk to a resource (you might imagine an RSS feed, or any other custom data format) that
Spring Batch doesn't know how to connect to.
Solution
You can easily write your own
ItemWriter
or
ItemReader
. The interfaces are drop dead simple and there's
not a lot of responsibility placed on the implementations.
How It Works
As easy and trivial as this process is to do, it's still not better than just reusing any of the numerous
provided options. If you look, you'll likely find something. There's support for writing JMS
(
JmsItemWriter
), JPA (
JpaItemWriter
), JDBC (
JdbcBatchItemWriter
), Files (
FlatFileItemWriter
),
iBatis (
IbatisBatchItemWriter
), and more. There's even support for “writing” by invoking a method
on a bean (
PropertyExtractingDelegatingItemWriter
) and passing to it as arguments the properties on
the
Item
to be written! There's a slightly smaller but impressive set of implementations for
ItemReader
implementations.
Writing a Custom ItemReader
The
ItemReader
example is trivial. Here an
ItemReader
is created that knows how to retrieve
UserRegistration
objects from an (remote procedure call (RPC) endpoint:
package com.apress.springenterpriserecipes.springbatch.solution2;
import java.util.Collection;
import java.util.Date;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ParseException;
import org.springframework.batch.item.UnexpectedInputException;
import org.springframework.beans.factory.annotation.Autowired;
import com.apress.springenterpriserecipes.springbatch.
➥
UserRegistrationService;
import com.apress.springenterpriserecipes.springbatch.solution1.
➥
UserRegistration;
public class UserRegistrationItemReader implements ItemReader<UserRegistration> {
@Autowired
private UserRegistrationService userRegistrationService;
Search WWH ::
Custom Search