Spring Batch:文件未被读取

时间:2016-10-12 16:42:36

标签: spring-batch

我正在尝试创建一个使用spring-batch-excel扩展的应用程序,以便能够读取用户通过Web界面上传的Excel文件,以便解析Excel文件中的地址。

当代码运行时,没有错误,但我得到的只是我的日志中的以下内容。即使我在处理器和写入器中都有log / syso(这些从未被调用过,而我可以想象的是它没有正确读取文件,并且没有返回任何数据来处理/写入)。是的,该文件实际上有数据,数千条记录。

Job: [FlowJob: [name=excelFileJob]] launched with the following parameters: [{file=Book1.xlsx}]
Executing step: [excelFileStep]
Job: [FlowJob: [name=excelFileJob]] completed with the following parameters: [{file=Book1.xlsx}] and the following status: [COMPLETED]

以下是我的JobConfig

@Configuration
@EnableBatchProcessing
public class AddressExcelJobConfig {

    @Bean
    public BatchConfigurer configurer(EntityManagerFactory entityManagerFactory) {
        return new CustomBatchConfigurer(entityManagerFactory);
    }

    @Bean
    Step excelFileStep(ItemReader<AddressExcel> excelAddressReader,
                       ItemProcessor<AddressExcel, AddressExcel> excelAddressProcessor,
                       ItemWriter<AddressExcel> excelAddressWriter, 
                       StepBuilderFactory stepBuilderFactory) {
        return stepBuilderFactory.get("excelFileStep")
                .<AddressExcel, AddressExcel>chunk(1)
                .reader(excelAddressReader)
                .processor(excelAddressProcessor)
                .writer(excelAddressWriter)
                .build();
    }

    @Bean
    Job excelFileJob(JobBuilderFactory jobBuilderFactory, 
                     @Qualifier("excelFileStep") Step excelAddressStep) {
        return jobBuilderFactory.get("excelFileJob")
                .incrementer(new RunIdIncrementer())
                .flow(excelAddressStep)
                .end()
                .build();
    }
}

以下是我的AddressExcelReader 后期绑定工作正常,没有错误。除了创建新的ClassPathResource和FileSystemResource之外,我还尝试加载给定文件名的资源。所有人都给了我相同的结果。

@Component
@StepScope
public class AddressExcelReader implements ItemReader<AddressExcel> {

    private PoiItemReader<AddressExcel> itemReader = new PoiItemReader<AddressExcel>();

    @Override
    public AddressExcel read()
            throws Exception, UnexpectedInputException, ParseException, NonTransientResourceException {
        return itemReader.read();
    }

    public AddressExcelReader(@Value("#{jobParameters['file']}") String file, StorageService storageService) {
        //Resource resource = storageService.loadAsResource(file);
        //Resource testResource = new FileSystemResource("upload-dir/Book1.xlsx");
        itemReader.setResource(new ClassPathResource("/upload-dir/Book1.xlsx"));
        itemReader.setLinesToSkip(1);
        itemReader.setStrict(true);
        itemReader.setRowMapper(excelRowMapper());
    }

    public RowMapper<AddressExcel> excelRowMapper() {
        BeanWrapperRowMapper<AddressExcel> rowMapper = new BeanWrapperRowMapper<>();
        rowMapper.setTargetType(AddressExcel.class);
        return rowMapper;
    }

}

以下是我的AddressExcelProcessor

@Component
public class AddressExcelProcessor implements ItemProcessor<AddressExcel, AddressExcel> {

    private static final Logger log = LoggerFactory.getLogger(AddressExcelProcessor.class);

    @Override
    public AddressExcel process(AddressExcel item) throws Exception {
        System.out.println("Converting " + item);
        log.info("Convert {}", item);
        return item;
    }

}

同样,这永远不会发挥作用(没有生成日志)。如果重要的话,这就是我从@PostMapping(“/”)的FileUploadController启动我的工作来处理文件上传,首先存储文件,然后运行作业:

@PostMapping("/")
public String handleFileUpload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {

    storageService.store(file);

    try {
        JobParameters jobParameters = new JobParametersBuilder()
                .addString("file", file.getOriginalFilename().toString()).toJobParameters();
        jobLauncher.run(job, jobParameters);
    } catch (JobExecutionAlreadyRunningException | JobRestartException | JobInstanceAlreadyCompleteException
            | JobParametersInvalidException e) {
        e.printStackTrace();
    }

    redirectAttributes.addFlashAttribute("message",
            "You successfully uploaded " + file.getOriginalFilename() + "!");

    return "redirect:/";
}

最后一点

这是我的AddressExcel POJO

import lombok.Data;

@Data
public class AddressExcel {

    private String address1;
    private String address2;
    private String city;
    private String state;
    private String zip;

    public AddressExcel() {}

}

更新(2016年10月13日) 从Nghia Do的评论中,我还创建了自己的RowMapper而不是使用BeanWrapper来查看是否存在问题。结果仍然相同。

public class AddressExcelRowMapper implements RowMapper<AddressExcel> {

    @Override
    public AddressExcel mapRow(RowSet rs) throws Exception {
        AddressExcel temp = new AddressExcel();

        temp.setAddress1(rs.getColumnValue(0));
        temp.setAddress2(rs.getColumnValue(1));
        temp.setCity(rs.getColumnValue(2));
        temp.setState(rs.getColumnValue(3));
        temp.setZip(rs.getColumnValue(4));

        return temp;
    }

}

1 个答案:

答案 0 :(得分:0)

似乎我需要的是将以下内容添加到我的ItemReader中:

itemReader.afterPropertiesSet();
itemReader.open(new ExecutionContext());