You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

迁移至Spring Batch 5.0后MySQL DataSource无法正常工作

问题分析与解决方案

迁移到Spring Batch 5.0(Spring Boot 3.0.2)后,作业仓库未写入MySQL而是使用内存数据库,主要由以下几个原因导致,对应解决方案如下:


1. 缺少MySQL驱动依赖

Spring Boot 3.x不再默认包含MySQL驱动,必须显式添加。在pom.xml中加入:

<dependency>
    <groupId>com.mysql</groupId>
    <artifactId>mysql-connector-j</artifactId>
    <scope>runtime</scope>
</dependency>

2. 未配置Spring Batch Schema初始化

Spring Boot默认仅对嵌入式数据库自动初始化Spring Batch的Schema,使用MySQL时需手动开启:
在application.properties中添加:

spring.batch.jdbc.initialize-schema=always

注:生产环境可根据需求改为never,提前手动执行Spring Batch官方提供的MySQL Schema脚本。

3. 优化数据源配置(推荐)

代码中硬编码创建DataSource的方式不够灵活,建议改用Spring Boot配置文件管理:
在application.properties中配置:

spring.datasource.url=jdbc:mysql://localhost:3306/batch_repo?serverTimezone=UTC
spring.datasource.username=root
spring.datasource.password=software
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver

之后可以移除DefaultBatchConfiguration中重写的getDataSource()方法,Spring Batch会自动注入Spring容器中的DataSource。

4. 修复Tasklet执行逻辑

你的Tasklet返回null会导致作业执行异常,无法生成正常的作业执行记录。修改Tasklet的返回值:

@Bean
public Tasklet myTasklet() {
    return (stepContribution, chunkContext) -> {
        System.out.println("Tasklet executed successfully");
        return RepeatStatus.FINISHED;
    };
}

完成以上修改后,重新启动应用,Spring Batch会自动初始化MySQL中的Schema,作业执行后即可在batch_repo库中看到batch_job_execution、batch_step_execution等表及对应执行记录。

内容的提问来源于stack exchange,提问作者Yossi R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 08:25:35