Spring Boot中Spring Batch任务未执行的问题求助
Spring Batch任务未执行排查与修复
问题概述
运行Spring Batch任务读取CSV并写入HSQL嵌入式数据库,预期每行数据写入时输出日志,但控制台无任何日志且无报错,任务未被调用。
排查与修复要点
1. 配置Job自动触发执行
Spring Boot默认不会自动启动定义的Batch Job,需添加触发逻辑:
@Component public class JobStarter implements ApplicationRunner { private final JobLauncher jobLauncher; private final Job importUserJob; public JobStarter(JobLauncher jobLauncher, Job importUserJob) { this.jobLauncher = jobLauncher; this.importUserJob = importUserJob; } @Override public void run(ApplicationArguments args) throws Exception { JobParameters jobParameters = new JobParametersBuilder() .addLong("runTime", System.currentTimeMillis()) // 唯一参数避免重复执行 .toJobParameters(); jobLauncher.run(importUserJob, jobParameters); } }
也可通过配置文件开启所有Job自动执行:
spring.batch.job.enabled=true
2. 调整日志级别配置
检查application.properties,确保Spring Batch及业务包的日志级别为INFO:
logging.level.org.springframework.batch=INFO logging.level.io.davidwilliford=INFO
若日志级别过高(如ERROR),会屏蔽任务执行的INFO级日志。
3. 补全MatchInput类的Getter/Setter方法
BeanWrapperFieldSetMapper依赖Getter/Setter映射CSV字段到对象,必须为MatchInput所有字段添加标准Getter/Setter,否则CSV读取失败导致任务中断。
4. 修复Match类的不完整方法
Match类中getId()方法仅声明无实现,且缺少其他属性的Getter/Setter,BeanPropertyItemSqlParameterSourceProvider无法获取属性值填充SQL参数,需补全:
public class Match { // ... 现有属性 ... public int getId() { return id; } public void setId(int id) { this.id = id; } // 补全其他所有属性的Getter/Setter }
5. 修正Listener中的SQL表名错误
JobCompletionNotificationListener中查询表名为match,但实体类标注表名为matches,修正SQL:
jdbcTemplate.query("SELECT home_team, away_team FROM matches", (rs, row) -> "Home Team: " + rs.getString(1) + " Away Team: " + rs.getString(2)) .forEach(System.out::println);
6. 完善MatchDataProcessor实现
确保MatchDataProcessor正确实现ItemProcessor<MatchInput, Match>接口,完成数据转换逻辑:
public class MatchDataProcessor implements ItemProcessor<MatchInput, Match> { @Override public Match process(MatchInput input) throws Exception { Match match = new Match(); // 转换match字段为id match.setId(Integer.parseInt(input.getMatch())); // 拆分score字段为主客队比分 String[] scoreParts = input.getScore().split("-"); match.setHome_score(scoreParts[0].trim()); match.setAway_score(scoreParts[1].trim()); // 映射其他属性 match.setDayofweek(input.getDayofweek()); match.setMatch_time(input.getMatch_time()); match.setHome_team(input.getHome_team()); match.setAway_team(input.getAway_team()); // 补全其余属性映射 return match; } }
内容的提问来源于stack exchange,提问作者David Williford
相关产品推荐
相关产品推荐

