SpringBatch的ItemWriterDemo
Posted syue
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBatch的ItemWriterDemo相关的知识,希望对你有一定的参考价值。
跟着视频写的一个小Demo
目录结构:
MyWriter.class
package com.practice.itemwriter; import org.springframework.batch.item.ItemWriter; import org.springframework.stereotype.Component; import java.util.List; @Component("myWriter") public class MyWriter implements ItemWriter<String> { @Override public void write(List<? extends String> items) throws Exception { System.out.println(items.size()); for(String str:items){ System.out.println(str); } } }
ItemWriterDemo.class
package com.practice.itemwriter; import org.springframework.batch.core.Job; import org.springframework.batch.core.Step; import org.springframework.batch.core.configuration.annotation.JobBuilderFactory; import org.springframework.batch.core.configuration.annotation.StepBuilderFactory; import org.springframework.batch.item.ItemReader; import org.springframework.batch.item.ItemWriter; import org.springframework.batch.item.support.ListItemReader; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import java.util.ArrayList; import java.util.List; @Configuration public class ItemWriterDemo { @Autowired private JobBuilderFactory jobBuilderFactory; @Autowired private StepBuilderFactory stepBuilderFactory; @Autowired @Qualifier("myWriter") private ItemWriter<String> myWriter; @Bean public Job itemWriterDemoJob(){ return jobBuilderFactory.get("itemWriterDemoJob").start(itemWriterDemoStep()).build(); } @Bean public Step itemWriterDemoStep() { return stepBuilderFactory.get("itemWriterDemoStep") .<String,String>chunk(10).reader(myRead()).writer(myWriter).build(); } public ItemReader<String> myRead() { List<String> items = new ArrayList<>(); for(int i = 0;i<=50;i++){ items.add("java"+i); } return new ListItemReader<String>(items); } }
DemoApplication
package com.practice.itemwriter; import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @EnableBatchProcessing public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
正常输出:
以上是关于SpringBatch的ItemWriterDemo的主要内容,如果未能解决你的问题,请参考以下文章
SpringBatch Sample (固定长格式文件读写)