Java Reference
In-Depth Information
St. Louis, NY
94935
As you would expect, calling an existing service with the item you've processed in your step is made
easy with Spring Batch. However, what if your service doesn't take the same object you're processing? If
you want to be able to extract values out of your item and pass them to your service, Spring Batch has
you covered. PropertyExtractingDelegatingItemWriter (yes, that really is its name) is next.
PropertyExtractingDelegatingItemWriter
The use case for ItemWriterAdapter is pretty simple. Take the item being processed, and pass it to an
existing Spring service. However, software is rarely that straightforward. Because of that, Spring Batch
has provided a mechanism to extract values from an item and pass them to a service as parameters. This
section looks at PropertyExtractingDelegatingItemWriter and how to use it with an existing service.
Although it has a long name,
org.springframework.batch.item.adapter.PropertyExtractingDelegatingItemWriter is a lot like the
ItemWriterAdapter . Just like ItemWriterAdapter , it calls a specified method on a referenced Spring
service. The difference is that instead of blindly passing the item being processed by the step,
PropertyExtractingDelegatingItemWriter passes only the attributes of the item that are requested. For
example, if you have an item of type Product that contains fields for a database id, name, price, and SKU
number, you're required to pass the entire Product object to the service method as with
ItemWriterAdapter . But with PropertyExtractingDelegatingItemWriter , you can specify that you only
want the database id and price to be passed as parameters to the service.
To look at this as an example, you can use the same customer input that you're familiar with by this
point. You add a method to the CustomerService Impl that allows you to log the address of the Customer
item being processed and use PropertyExtractingDelegatingItemWriter to call the new method. Let's
start by looking at the updated CustomerServiceImpl (see Listing 9-44).
Listing 9-44. CustomerServiceImpl with logAddress()
package com.apress.springbatch.chapter9;
public class CustomerServiceImpl {
public void logCustomer(Customer cust) {
System.out.println("I just saved " + cust);
}
public void logAddress(String address,
String city,
String state,
String zip) {
System.out.println("I just saved the address:\n" + address + "\n" +
city + ", " + state + "\n" + zip);
}
}
As you can see in Listing 9-44, the logAddress method doesn't take the Customer item. Instead it
takes values that you have within it. To use this method, you use
PropertyExtractingDelegatingItemWriter to extract the address fields (address, city, state, and zip) from
each Customer item and call the service with the values it receives. To configure this ItemWriter, you pass
 
 
Search WWH ::




Custom Search