当 application.properties 中的值发生变化时,as spring 属性 多久更新一次?

How often does as spring property get updated when value in application.properties changes?

我会在每小时的预定时间执行一项任务,并使用@Scheduled 执行以下操作。下面的代码确实在每小时 5 分钟后执行任务。但是,如果我将应用程序启动后的 属性 更改为“ 0 10 * * * *”,它会读取该值并将任务计划更改为小时后 10 分钟的 运行 吗?

@Component
public class DataCleanupTask {
    private static final Logger LOGGER = LoggerFactory.getLogger(DataCleanupTask.class);
    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-DD HH:mm:ss a");

    @Scheduled(cron = "${data.cleanup.task.schedule.cron}")
    public void cleanupData() {
        LOGGER.debug("Starting data cleanup at " + dateFormat.format(new Date()));
    }
}

# application.properties
# Schedules a task to run 5 minutes after the hour, every hour
data.cleanup.task.schedule.cron=0 5 * * * *

在 Spring 应用程序中,系统启动时(通过 BeanFactoryPostProcessor)读取属性并处理对它们的所有引用;在应用程序启动后更改属性文件不会有任何影响,直到应用程序重新启动。

为了在运行时重新配置您的系统,您需要公开从外部修改它们的方法,例如使用 JMX。

正如 Marthursson 所说:Spring 在启动时应用,但之后不会刷新 属性 值。

如果您正在寻找这种功能,您可能需要尝试 apache commons-configuration

这是一篇博客 post,展示了如何将它与 spring 一起使用以观察属性文件中的更改:Reloadable properties file with Spring using Apache Commons Configuration