Dee*_*aya 5 java spring spring-batch java-8 spring-boot
我一直在努力使用 Spring Batch 访问作业的作业参数。这是到目前为止我的实现。
@Configuration
@EnableBatchProcessing
@PropertySource("classpath:batch.properties")
public class CSVBatchServiceImpl extends StepExecutionListenerSupport implements CSVBatchService {
private static final Logger LOGGER = LoggerFactory.getLogger(CSVBatchServiceImpl.class);
@Autowired
public JobBuilderFactory jobBuilderFactory;
@Autowired
public StepBuilderFactory stepBuilderFactory;
private QuestionReader questionReader = new QuestionReader();
@Bean(name = "importQuestionsJob")
public Job importQuestionsJob() {
return jobBuilderFactory.get("importQuestionsJob")
.incrementer(new RunIdIncrementer())
.flow(step1())
.end()
.build();
}
@Bean
public Step step1() {
return stepBuilderFactory.get("step1")
.<Question, Question>chunk(2)
.reader(questionReader.reader())
.processor(processor())
.build();
}
@Bean
public QuestionProcessor processor() {
return new QuestionProcessor();
}
}
class QuestionReader extends StepExecutionListenerSupport {
private static final Logger LOGGER = LoggerFactory.getLogger(QuestionReader.class);
//TODO: remove this
private static JsonNode getJsonNode(String str) {
try {
ObjectMapper mapper = new ObjectMapper();
return mapper.readTree(str);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Bean
public FlatFileItemReader<Question> reader() {
FlatFileItemReader<Question> reader = new FlatFileItemReader<>();
//TODO get this as a parameter
reader.setResource(new ClassPathResource("duplicateLabels.csv"));
reader.setLinesToSkip(1);
reader.setLineMapper(new DefaultLineMapper<Question>() {{
setLineTokenizer((new DelimitedLineTokenizer() {{
setNames(new String[]{"label", "body", "real_answer"});
}}));
setFieldSetMapper(new QuestionFieldSetMapper());
}});
return reader;
}
private static class QuestionFieldSetMapper implements FieldSetMapper<Question> {
public Question mapFieldSet(FieldSet fieldSet) {
Question question = new Question();
question.setLabel(fieldSet.readString(0));
question.setBody(getJsonNode(fieldSet.readString(1)));
question.setRealAnswer(getJsonNode(fieldSet.readString(2)));
return question;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我这样称呼这份工作:
JobParameters parameters = new JobParametersBuilder()
.addLong("time", System.currentTimeMillis())
.addString("filePath", "file.csv")
.toJobParameters();
jobLauncher.run(importQuestionsJob, parameters);
Run Code Online (Sandbox Code Playgroud)
如何访问 reader 函数内的 filePath 参数?
你应该能够做到,
@Value("#{jobParameters['filePath']}") String filePath;
Run Code Online (Sandbox Code Playgroud)
如有任何问题,您可以尝试将阅读器放入@StepScope.
| 归档时间: |
|
| 查看次数: |
21138 次 |
| 最近记录: |