1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.springframework.batch.sample.domain.trade.internal;
18
19 import java.util.Collections;
20
21 import org.springframework.batch.item.ExecutionContext;
22 import org.springframework.batch.item.ItemStream;
23 import org.springframework.batch.item.ItemWriter;
24 import org.springframework.batch.sample.domain.trade.CustomerCredit;
25 import org.springframework.batch.sample.domain.trade.CustomerCreditDao;
26 import org.springframework.beans.factory.DisposableBean;
27
28
29
30
31
32
33
34 public class FlatFileCustomerCreditDao implements CustomerCreditDao,
35 DisposableBean {
36
37 private ItemWriter<String> itemWriter;
38
39 private String separator = "\t";
40
41 private volatile boolean opened = false;
42
43 public void writeCredit(CustomerCredit customerCredit) throws Exception {
44
45 if (!opened) {
46 open(new ExecutionContext());
47 }
48
49 String line = "" + customerCredit.getName() + separator
50 + customerCredit.getCredit();
51
52 itemWriter.write(Collections.singletonList(line));
53 }
54
55 public void setSeparator(String separator) {
56 this.separator = separator;
57 }
58
59 public void setItemWriter(ItemWriter<String> itemWriter) {
60 this.itemWriter = itemWriter;
61 }
62
63 public void open(ExecutionContext executionContext) throws Exception {
64 if (itemWriter instanceof ItemStream) {
65 ((ItemStream) itemWriter).open(executionContext);
66 }
67 opened = true;
68 }
69
70 public void close() throws Exception {
71 if (itemWriter instanceof ItemStream) {
72 ((ItemStream) itemWriter).close();
73 }
74 }
75
76
77
78
79
80
81 public void destroy() throws Exception {
82 close();
83 }
84
85 }