preface

A female student at The Tsinghua Academy of Fine Arts claimed that a male student touched her PP through the cover of a bag and posted his identity information on social media, which nearly killed him.

Spring Batch validability

We often need to read a lot of data, some of which may not meet our expectations, such as reading a list of users from the interface and having a negative age field, which may cause the program to break or skip processing and move on to the next item

Spring Batch validability example

Reader processor processor processor processor Processor Processor processor processor

@Componentpublic class QingGirlProcessor implements ItemProcessor<Girl, String> {@override public String process(Girl Girl) throws Exception {return girl.getName() + "say I was touched PP"; }}Copy the code

Use composition to concatenate the validated processor with the processor of the above business:

@Configurationpublic class ProcessorConfig {    @Autowired    private QingGirlProcessor qingGirlProcessor;    @Bean    public BeanValidatingItemProcessor<Girl> girlBeanValidatingItemProcessor() throws Exception {        BeanValidatingItemProcessor<Girl> validator = new BeanValidatingItemProcessor<>();        validator.setFilter(true);        validator.afterPropertiesSet();        return validator;    }    @Bean    public ItemProcessor<Girl, String> girlStringItemProcessor() throws Exception {        List<ItemProcessor> list = new ArrayList<>();        list.add(girlBeanValidatingItemProcessor());        list.add(qingGirlProcessor);        CompositeItemProcessor compositeItemProcessor =            new CompositeItemProcessor<>();        compositeItemProcessor.setDelegates(list);        compositeItemProcessor.afterPropertiesSet();        return compositeItemProcessor;    }}
Copy the code

Task configuration:

final String JOB_NAME = "demo4QingGirl"; List<Girl> girlList = new ArrayList<>(); for (int i = 0; i < 10; i++) { girlList.add(i % 2 == 0 ? New Girl() : New Girl(" * * * ")); }final ListReader<Girl> reader = new ListReader<>(girlList); final Job girlJob = jobBuilderFactory.get(JOB_NAME) .flow(stepBuilderFactory.get(JOB_NAME) .<Girl, String>chunk(2).reader(reader) .processor(girlStringItemProcessor).writer(printWriter).build()) .end().build(); jobLauncher.run(girlJob, new JobParametersBuilder() .addDate("start_time", new Date()).toJobParameters());Copy the code

Output:

Don * jing says he was touched. Don * jing says he was touched. Don * jing says he was touchedCopy the code

This is what our Girl class does:

@Data@AllArgsConstructor@NoArgsConstructorpublic class Girl { @NotBlank private String name; }Copy the code

This ensures that only the data that meets expectations is processed

Wechat Official Account: