Spring Boot在Service方法中使用“ FlatFileItemReader”读取CSV文件

时间:2019-02-06 07:47:50

标签: spring-batch

我将开发一个应用程序,尝试使用Spring FlatFileItemReader对象读取CSV文件。我喜欢在将要调用一种方法来执行阅读过程的服务中使用服务。但是我没有直接使用FlatFileItemReader和其他的配置bean对象。我的原型波纹管的一个例子。

public void executeCsvReading(){

    FlatFileItemReader<SomeModel> reader = new FlatFileItemReader<SomeModel>();

    reader.setResource(new ClassPathResource("someFile.csv"));

    reader.setLineMapper(new DefaultLineMapper<SomeModel>() {
        {

            setLineTokenizer(new DelimitedLineTokenizer() {
                {
                    setNames(new String[] { "somefield1", "somefield2" });
                }
            });

            setFieldSetMapper(new BeanWrapperFieldSetMapper<SomeModel>() {
                {
                    setTargetType(SomeModel.class);
                }
            });
        }
    });

// But how do I start this Job?
   Job job = jobBuilderFactory
            .get("readCSVFilesJob")
            .incrementer(new RunIdIncrementer())
            .start(step)
            .build();

   Step step = stepBuilderFactory.get("step1").<SomeModel, SomeModel>chunk(5)
            .reader(reader)
            .writer(new WriteItemsOn()) // Call WriteItemsOn class constructor
            .build();
}

public class WriteItemsOn implements ItemWriter<User> {

    @Override
    public void write(List<? extends SomeModel> items) throws Exception {
        // TODO Auto-generated method stub
        for (SomeModel item : items) {
            System.out.println("Item is " + item.someMethod()");
        }
    }
}

1 个答案:

答案 0 :(得分:0)

  

//但是如何开始这项工作?

要开始工作,您需要使用JobLauncher。例如:

SimpleJobLauncher jobLauncher = new SimpleJobLauncher();
//jobLauncher.setJobRepository(yourJobRepository);
//jobLauncher.setTaskExecutor(yourTaskExecutor);
jobLauncher.afterPropertiesSet();
jobLauncher.run(job, new JobParameters());

但是,使用这种方法,您将需要自己配置Spring Batch(JobRepositoryJobLauncher等)所需的基础结构bean。

我建议使用典型的Spring Batch作业配置,并通过方法executeCsvReading运行您的作业。这是一个示例:

import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableBatchProcessing
public class MyJob {

    private final JobBuilderFactory jobBuilderFactory;

    private final StepBuilderFactory stepBuilderFactory;

    public MyJob(JobBuilderFactory jobBuilderFactory, StepBuilderFactory stepBuilderFactory) {
        this.jobBuilderFactory = jobBuilderFactory;
        this.stepBuilderFactory = stepBuilderFactory;
    }

    @Bean
    public Step step() {
        return stepBuilderFactory.get("step")
                .tasklet((contribution, chunkContext) -> {
                    System.out.println("hello world");
                    return RepeatStatus.FINISHED;
                })
                .build();
    }

    @Bean
    public Job job() {
        return jobBuilderFactory.get("job")
                .start(step())
                .build();
    }

}

使用此作业配置后,您可以加载Spring应用程序上下文并按以下方式启动作业:

public void executeCsvReading() {
   ApplicationContext context = new AnnotationConfigApplicationContext(MyJob.class);
   JobLauncher jobLauncher = context.getBean(JobLauncher.class);
   Job job = context.getBean(Job.class);
   jobLauncher.run(job, new JobParameters());
}

请注意,可以在方法executeCsvReading外部之外完成Spring应用程序上下文的加载,这样,每次调用此方法时就不会加载它。使用这种方法,您不必自己配置Spring Batch所需的基础结构Bean,它们将自动创建并添加到应用程序上下文中。当然可以根据需要覆盖它们。

注意:如果将MyJob配置类放在Spring Boot应用程序的包中,则默认情况下,Spring Boot将在启动时执行作业。您可以通过在应用程序属性中添加spring.batch.job.enabled=false来禁用此行为。

希望这会有所帮助。