创建SpringBatchConfig时如何重写getJobExplorer() 解决调用空指针问题
问题原因
你当前代码中直接返回的jobExplorer成员变量未完成初始化赋值,所以调用时会抛出NullPointerException。
正确重写方案
方案1:手动通过JobExplorerFactoryBean构建(通用方案,适用于所有Spring Batch环境)
通过Spring Batch官方提供的JobExplorerFactoryBean工厂类完成实例初始化,需要依赖数据源和事务管理器,示例代码如下:
import org.springframework.batch.core.explore.JobExplorer; import org.springframework.batch.core.explore.support.JobExplorerFactoryBean; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.PlatformTransactionManager; import javax.sql.DataSource; // 类内的成员变量注入 @Autowired private DataSource dataSource; @Autowired private PlatformTransactionManager transactionManager; @Override @Bean public JobExplorer getJobExplorer() throws Exception { JobExplorerFactoryBean explorerFactory = new JobExplorerFactoryBean(); // 配置数据源,用于访问Spring Batch元数据表 explorerFactory.setDataSource(dataSource); // 配置事务管理器 explorerFactory.setTransactionManager(transactionManager); // 可选自定义配置 // explorerFactory.setTablePrefix("MY_BATCH_"); // 自定义元数据表前缀 // explorerFactory.setSerializer(new Jackson2ExecutionContextStringSerializer()); // 自定义上下文序列化规则 // 完成属性校验和实例初始化 explorerFactory.afterPropertiesSet(); return explorerFactory.getObject(); }
方案2:复用Spring Boot自动配置的实例(仅Spring Boot环境适用)
如果你的项目是Spring Boot环境且没有排除Batch自动配置,框架已经自动初始化好了JobExplorer实例,直接注入后返回即可:
import org.springframework.batch.core.explore.JobExplorer; import org.springframework.beans.factory.annotation.Autowired; @Autowired private JobExplorer autoConfiguredJobExplorer; @Override @Bean public JobExplorer getJobExplorer() throws Exception { return autoConfiguredJobExplorer; }
注意事项
- 两种方案都需要保证项目中已正确创建Spring Batch的元数据表,配置的数据源拥有这些表的访问权限
- 方案2使用前确认启动类上没有添加
@EnableBatchProcessing注解,Spring Boot 2.2+之后添加该注解会覆盖自动配置,导致无法注入默认的JobExplorer实例
内容的提问来源于stack exchange,提问作者Akhachkhouch
相关产品推荐
相关产品推荐

