Spring Batch 5迁移遇DataSource兼容问题:API仍依赖javax而非jakarta
Spring Batch 5 JDBC组件数据源适配问题解决方案
问题澄清
你提到的jakarta.activation.DataSource并非JDBC规范的数据源类,Jakarta EE中对应的JDBC数据源是jakarta.sql.DataSource,而Spring Batch 5的JDBC组件(如JdbcCursorItemReader)依赖的是JDBC API中的javax.sql.DataSource——这是因为JDBC规范本身在Jakarta EE 9+中只是包名从javax.sql迁移到jakarta.sql,两者是等价的API,只是包名变更。
解决步骤
修正数据源注入类型
替换错误的jakarta.activation.DataSource为正确的jakarta.sql.DataSource:@Configuration public class Config { @Autowired private jakarta.sql.DataSource dataSource; @Bean public ItemReader<T> reader() { JdbcCursorItemReader<T> reader = new JdbcCursorItemReader<>(); reader.setDataSource(dataSource); // 补充其他必要配置,如SQL语句、RowMapper等 reader.setSql("SELECT * FROM your_table"); reader.setRowMapper(new BeanPropertyRowMapper<>(YourEntity.class)); return reader; } }确保依赖正确对齐
- 确认项目中使用的Spring Batch 5版本已经适配Jakarta EE,依赖的
spring-batch-core等构件是基于Jakarta的版本(Spring Batch 5.x默认就是)。 - 数据库驱动和连接池依赖(如HikariCP、Tomcat JDBC)也需要使用适配Jakarta EE 9+的版本,确保它们提供的是
jakarta.sql.DataSource实现。
- 确认项目中使用的Spring Batch 5版本已经适配Jakarta EE,依赖的
类型转换处理(极端冲突场景)
若因依赖冲突导致数据源类型不兼容,可以通过手动包装适配:// 手动委托jakarta.sql.DataSource实现javax.sql.DataSource接口 reader.setDataSource(new javax.sql.DataSource() { @Override public Connection getConnection() throws SQLException { return dataSource.getConnection(); } @Override public Connection getConnection(String username, String password) throws SQLException { return dataSource.getConnection(username, password); } @Override public PrintWriter getLogWriter() throws SQLException { return dataSource.getLogWriter(); } @Override public void setLogWriter(PrintWriter out) throws SQLException { dataSource.setLogWriter(out); } @Override public void setLoginTimeout(int seconds) throws SQLException { dataSource.setLoginTimeout(seconds); } @Override public int getLoginTimeout() throws SQLException { return dataSource.getLoginTimeout(); } @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { return dataSource.getParentLogger(); } @Override public <T> T unwrap(Class<T> iface) throws SQLException { return dataSource.unwrap(iface); } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return dataSource.isWrapperFor(iface); } });
关键说明
Spring Batch 5的JDBC组件并未停留在javax.sql,而是通过API兼容处理支持jakarta.sql.DataSource——核心问题是你注入了错误的数据源类型(jakarta.activation.DataSource是邮件相关的数据源,和JDBC无关)。
内容的提问来源于stack exchange,提问作者CODI
相关产品推荐
相关产品推荐

