我将 Spring Batch 与 Spring Boot 一起使用,这是我的主要课程。
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
这是我的配置类
@Configuration
public class AppConfig {
@Bean
public MyObject getObject() {
return new MyObject();
}
}
@Configuration
@EnableBatchProcessing
public class BatchConfiguration {
private static final String OVERRIDDEN_BY_EXPRESSION = null;
@Autowired
private JobBuilderFactory jobs;
@Autowired
private StepBuilderFactory steps;
@Bean
public Job job() {
return jobs.get(Constants.FULL_JOB_NAME)
.start(stepProcessDocument())
.build();
}
@Bean
protected Step stepProcessDocument() {
return steps.get(Constants.STEP_PROCESS_DOCUMENT_NAME)
.<Document,Document>chunk(10)
.reader(buildItemReader(OVERRIDDEN_BY_EXPRESSION))
.processor(buildItemProcessor())
.writer(buildItemWriter(OVERRIDDEN_BY_EXPRESSION))
.build();
}
@Bean
@StepScope
protected ItemReader<Document> buildItemReader(@Value("#{jobParameters[" + Constants.PARAM_JOB_PARAMETER + "]}") String param) {
ItemStreamReader<Document> reader = new CustomItemReader(param);
reader.open(new ExecutionContext());
return reader;
}
@Bean
protected ItemProcessor<Document, Document> buildItemProcessor() {
return new CustomItemProcessor();
}
@Bean
@StepScope
protected ItemWriter<Document> buildItemWriter(@Value("#{jobParameters[" + Constants.PARAM_JOB_PARAMETER + "]}") String param) {
ItemStreamWriter<Document> writer = new CustomItemWriter(param);
writer.open(new ExecutionContext());
return writer;
}
@Bean
public JobRegistryBeanPostProcessor jobRegistryBeanPostProcessor(JobRegistry jobRegistry) {
JobRegistryBeanPostProcessor jobRegistryBeanPostProcessor = new JobRegistryBeanPostProcessor();
jobRegistryBeanPostProcessor.setJobRegistry(jobRegistry);
return jobRegistryBeanPostProcessor;
}
}
这是我在应用程序中使用的自定义文件阅读器。
public class CustomItemReader implements ItemStreamReader<Document> {
@Autowired
private MyObject myObject;
private int count = 0;
private String param;
public CustomItemReader(String param) {
this.param = param;
}
@Override
public void open(ExecutionContext executionContext)
throws ItemStreamException {
myObject.open(); //myObject is null
}
@Override
public void update(ExecutionContext executionContext)
throws ItemStreamException {
// TODO Auto-generated method stub
}
@Override
public void close() throws ItemStreamException {
myObject.close();
}
@Override
public Document read() throws Exception, UnexpectedInputException,
ParseException, NonTransientResourceException {
myObject.doStuff();
count++;
if(count == 5) {
return null;
}
return new Document();
}
我在 myObject 上遇到了 Java 空指针异常。为什么我不能在 ItemStreamReader open 方法中自动装配 java 对象?