【Spring Batch学习笔记】2:Reader-Processor-Writer操作csv文件的例子

参考:1,2

程序结构

【Spring Batch学习笔记】2:Reader-Processor-Writer操作csv文件的例子_第1张图片

pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>

    <groupId>org.lzhgroupId>
    <artifactId>testSpringBatchartifactId>
    <version>1.0-SNAPSHOTversion>

    <dependencies>
        
        <dependency>
            <groupId>org.springframework.batchgroupId>
            <artifactId>spring-batch-coreartifactId>
            <version>3.0.7.RELEASEversion>
        dependency>
    dependencies>

project>

applicationContext.xml


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    <bean id="jobLauncher" class="org.springframework.batch.core.launch.support.SimpleJobLauncher">
        
        <property name="jobRepository" ref="jobRepository"/>
    bean>
    
    <bean id="jobRepository" class="org.springframework.batch.core.repository.support.MapJobRepositoryFactoryBean"/>
    
    <bean id="transactionManager" class="org.springframework.batch.support.transaction.ResourcelessTransactionManager"/>
beans>

batch.xml


<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:batch="http://www.springframework.org/schema/batch"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/batch
        http://www.springframework.org/schema/batch/spring-batch.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    
    <import resource="applicationContext.xml"/>

    

    <batch:job id="csvJob">
        
        <batch:step id="csvstep">
            
            <batch:tasklet transaction-manager="transactionManager">
                
                
                
                <batch:chunk reader="csvItemReader" processor="csvItemProcessor" writer="csvItemWriter"
                             commit-interval="1"/>
            batch:tasklet>
        batch:step>
    batch:job>

    

    
    <bean id="csvItemReader" class="org.springframework.batch.item.file.FlatFileItemReader" scope="step">
        
        <property name="resource" value="classpath:inputFile.csv"/>
        
        <property name="lineMapper">
            
            <bean class="org.springframework.batch.item.file.mapping.DefaultLineMapper">
                
                <property name="lineTokenizer" ref="lineTokenizer"/>
                
                <property name="fieldSetMapper" ref="fieldSetMapper"/>
            bean>
        property>
    bean>

    
    <bean id="lineTokenizer" class="org.springframework.batch.item.file.transform.DelimitedLineTokenizer">
        
        <property name="delimiter" value=","/>
        
        <property name="names">
            <list>
                <value>idvalue>
                <value>namevalue>
                <value>agevalue>
                <value>scorevalue>
            list>
        property>
    bean>

    
    <bean id="fieldSetMapper" class="org.springframework.batch.item.file.mapping.BeanWrapperFieldSetMapper">
        
        <property name="prototypeBeanName" value="student"/>
    bean>

    
    <bean id="student" class="org.lzh.Student"/>

    

    
    
    <context:component-scan base-package="org.lzh"/>

    

    
    <bean id="csvItemWriter" class="org.springframework.batch.item.file.FlatFileItemWriter">
        
        <property name="resource" value="file:src/main/resources/outputFile.csv"/>
        
        <property name="lineAggregator">
            
            <bean class="org.springframework.batch.item.file.transform.DelimitedLineAggregator">
                
                <property name="delimiter" value=","/>
                
                <property name="fieldExtractor">
                    <bean class="org.springframework.batch.item.file.transform.BeanWrapperFieldExtractor">
                        
                        <property name="names" value="name,age,score"/>
                    bean>
                property>
            bean>
        property>
    bean>

beans>

CsvItemProcessor类

package org.lzh;

//注意不是这个ItemProcessor
//import javax.batch.api.chunk.ItemProcessor;

import org.springframework.batch.item.ItemProcessor;
import org.springframework.stereotype.Component;

//自定义的处理类,需要实现ItemProcessor泛型接口,并实现其process方法
@Component("csvItemProcessor")
public class CsvItemProcessor implements ItemProcessor<Student,Student> {

    //对Reader获取的数据进行处理,传入的是Reader以后的Java对象,返回的是处理之后的Java对象,在这里都是Student对象
    @Override
    public Student process(Student student) throws Exception {
        //对Reader读取来的POJO对象做一些简单处理
        student.setName("SB"+student.getName());
        student.setAge(20);
        student.setScore(student.getScore()+20);
        //处理后的结果将传递给Writer
        return student;
    }
}

Student类

package org.lzh;

public class Student {
    private int id;
    private String name;
    private int age;
    private double score;

    //getter和setter
}

Main类

package org.lzh;

import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobExecution;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersInvalidException;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.repository.JobExecutionAlreadyRunningException;
import org.springframework.batch.core.repository.JobInstanceAlreadyCompleteException;
import org.springframework.batch.core.repository.JobRestartException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String[] args) {
        //batch.xml导入了applicationConext.xml,所以只写batch.xml就可以一并加入上下文
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("batch.xml");
        //Spring Batch的作业启动器,在applicationContext.xml中配置为了bean
        JobLauncher jobLauncher = (JobLauncher) applicationContext.getBean("jobLauncher");
        //在batch.xml中配置的一个作业
        Job job = (Job) applicationContext.getBean("csvJob");


        try {
            //开始执行这个作业,获得处理结果(要运行的job,job参数对象)
            JobExecution result = jobLauncher.run(job, new JobParameters());
            //输出处理结果看一下
            System.out.println("处理结果:" + result.toString());
        } catch (JobExecutionAlreadyRunningException e) {
            e.printStackTrace();
        } catch (JobRestartException e) {
            e.printStackTrace();
        } catch (JobInstanceAlreadyCompleteException e) {
            e.printStackTrace();
        } catch (JobParametersInvalidException e) {
            e.printStackTrace();
        }

    }
}

inputFile.csv

1,刘知昊,21,40
2,lzh,10,33

运行结果

这里写图片描述
这里写图片描述

你可能感兴趣的:(Spring,Batch,csv,#,Spring,Batch)