Spring batch 读取xml文件 转换为bean

需要引入

    
            com.thoughtworks.xstream
            xstream
            1.4.11.1
        

reader

public class CusXmlReader extends StaxEventItemReader {

    private String name = this.getClass().getSimpleName();

    private String resPath;

    public CusXmlReader(String resPath){
        this.resPath = resPath;
        init();
    }

    private void init(){


        XStreamMarshaller xStreamMarshaller = new XStreamMarshaller();

        setName(name);
        setResource(new ClassPathResource(resPath));


        String[] names = new String[]{"user","people"};
        /*如果只有一种数据类型 可以使用这个*/
//        setFragmentRootElementName("user");
        /*如果有多种数据类型使用这个*/
        setFragmentRootElementNames(names);

        Map aliases = new HashMap<>();
        aliases.put("user", User.class);
        aliases.put("name", String.class);
        aliases.put("tag", String.class);
        aliases.put("phone", String.class);
        aliases.put("address", String.class);
        aliases.put("cardNum", String.class);
        aliases.put("time", String.class);

       aliases.put("people", People.class);
        xStreamMarshaller.setAliases(aliases);

        setUnmarshaller(xStreamMarshaller);
    }
}

writer

public class CusXmlFlatItemWriter extends FlatFileItemWriter {

   private String funcName = this.getClass().getSimpleName();
   private String filePath;
   private FileSystemResource fileSystemResource;
   public CusXmlFlatItemWriter(String filePath){
       this.filePath = filePath;
       init();
       fileSystemResource = new FileSystemResource("E:\\code\\user.txt");
       setResource(fileSystemResource);
   }

   private void init(){
       setName(funcName);
       setAppendAllowed(true);
       /*设置 处理java对象的存储方式*/
       DelimitedLineAggregator lineAggregator = new DelimitedLineAggregator();
       lineAggregator.setDelimiter(",");
       setSaveState(false);
       setLineAggregator(lineAggregator);
       /*设置 是否 追加 还是 覆盖*/
       setAppendAllowed(false);
   }

   @Override
   public String doWrite(List items) {

       StringBuilder lines = new StringBuilder();
       Iterator var3 = items.iterator();

       while(var3.hasNext()) {
           Base item = (Base) var3.next();
           if(item.getTag().isEmpty()){
               item.setTag("1");
           }
           ((DelimitedLineAggregator)this.lineAggregator).setFieldExtractor(getBeanWrapperByTag(item.getTag()));
           lines.append(this.lineAggregator.aggregate(item)).append(this.lineSeparator);
       }

       return lines.toString();
   }

   private BeanWrapperFieldExtractor getBeanWrapperByTag(String tag){
       Field[] fields ;
       if(tag.equals("1")){
            fields = User.class.getDeclaredFields();
       }else{
           fields = People.class.getDeclaredFields();
       }

       String[] names = new String[fields.length];
       for(int i =0 ;i

运行

@SpringBootTest
public class XmlReaderTest {

    @Autowired
    private JobLauncher jobLauncher;

    @Autowired
    public JobBuilderFactory jobBuilderFactory;
    @Autowired
    public StepBuilderFactory stepBuilderFactory;


    private Step createStep(){
        String name = User.class.getName();
        Step  step =stepBuilderFactory.get(name)
                .chunk(1)
                .reader(new CusXmlReader("user.xml"))
                .writer(new CusXmlFlatItemWriter("user_writer.txt"))
                .build();

        return step;
    }

    private Job createJob(){
        String name = User.class.getName();
        return jobBuilderFactory.get(name).flow(createStep())
                .end().build();
    }
    @Test
    public  void runJob() throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException {
        //构建参数
        JobParameters jobParameters = new JobParametersBuilder()
                .toJobParameters();
        jobLauncher.run(createJob(),jobParameters);
    }
}

读取xml内容


    
1 gy phone1
12123123
password carNum
1 gy phone2
1231232
password carNum
2 gy phone peoplePassWord

你可能感兴趣的:(Spring batch 读取xml文件 转换为bean)