【问题标题】:Java LocalDate is not working within Spring beanJava LocalDate 在 Spring bean 中不起作用
【发布时间】:2023-03-20 18:07:02
【问题描述】:

我正在从事 Spring Batch 项目。我有从 SQL Server DB 读取数据的 bean。在读取查询中,我设置日期以从表中提取信息。问题是我使用String.format() 方法使用LocalDate 设置查询日期参数。我必须在当前日期添加一天。 bean 正在初始化,没有任何问题,在第一次运行时,查询按要求运行,但在连续运行期间,LocalDate 仅生成当前日期而不添加 1 天。

@Bean
public JdbcCursorItemReader<SchoolOrders> getOrdersInAdvance(){
JdbcCursorItemReader<SchoolOrders> jdbcCursorReader = new JdbcCursorItemReader();
String query = String.format("SELECT ORDER_NUMBER,STORE_NUMBER,PAYMENTINFO FROM ORDERS WHERE ORDER_DATE=%1$s",new Object[]{LocalDate.now(ZoneID.of("Asia/Kolkata")).plusDays(1)});
jdbcCursorReader .setDataSource(dataSource);
jdbcCursorReader .setSql(query);
jdbcCursorReader .setVerifyCurosrPosition(true);
jdbcCursorReader .setRowMapper(new BeanPropertyMapper<SchoolOrders>(SchoolOrders.class));
returns jdbcCursorReader;
}

我知道LocalDate 是不可变的,但日期不会保留在对象级别并立即生成。

谁能帮我解决这个问题!提前致谢。

【问题讨论】:

  • 连续运行是什么意思?
  • 使用 Dateformatter 将 LocalDate 格式化为字符串
  • @DeepakKumar 该作业每天运行一次,在第一次运行期间(服务器启动后)它按预期工作。但是第二天它会以特定日期的日期运行,而不是定义的 1 天。
  • @Rono 是的,我也试过了,它没有按预期工作。
  • @JayendranGurumoorthy 你检查第三天了吗?似乎是时区问题,可能数据库和系统未与同一时区同步。并且 LocalDate 不存储时区信息。

标签: java spring spring-boot spring-batch


【解决方案1】:

使用@Bean 指定JdbcCursorItemReader&lt;SchoolOrders&gt; 会产生singleton-scoped bean (default)。因此,getOrdersInAdvance() 方法只完整运行一次以配置 Spring Bean,并且所有后续调用都将简单地返回缓存的 bean,除非 - 正如您所观察到的 - 应用程序重新启动。

如果 Spring Bean 中有一个日期/时间敏感项,每次执行 JobStep 时都需要刷新,则可以分别使用 @JobScope@StepScope 注释该 bean 方法.

根据我对您的理解,我建议您首先尝试将您的 JdbcCursorItemReader 配置为工作范围。

@Bean
@JobScope
public JdbcCursorItemReader<SchoolOrders> getOrdersInAdvance(){
  JdbcCursorItemReader<SchoolOrders> jdbcCursorReader = new JdbcCursorItemReader();
  String query = String.format("SELECT ORDER_NUMBER,STORE_NUMBER,PAYMENTINFO FROM ORDERS WHERE ORDER_DATE=%1$s",new Object[]{LocalDate.now(ZoneID.of("Asia/Kolkata")).plusDays(1)});
  jdbcCursorReader .setDataSource(dataSource);
  jdbcCursorReader .setSql(query);
  jdbcCursorReader .setVerifyCurosrPosition(true);
  jdbcCursorReader .setRowMapper(new BeanPropertyMapper<SchoolOrders>(SchoolOrders.class));
  return jdbcCursorReader;
}

我还建议您阅读 late binding of job and step attributes 的 Spring Batch 文档。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-04
    • 1970-01-01
    • 1970-01-01
    • 2021-09-20
    • 1970-01-01
    • 1970-01-01
    • 2017-10-04
    • 2022-01-09
    相关资源
    最近更新 更多