首页 > 解决方案 > 如何在 Spring 中从文件读取参数到 Schedule 注释?

问题描述

我在 c:\Temp 文件夹中创建文件 init.txt。

login=rtyhjmdsf
password=cxzxdrfks
fixrate=6000

如何从我的文件中读取参数 'fixrate' 到 Spring 中的 Schedule 注释?如何在 SpEL 中将字符串转换为 Long?

这种收缩不起作用(

@Component
@PropertySource("file:c:\temp\init.txt")
class CronSchedule {

@Scheduled(fixedRate = "#{Long(scheduler[fixrate])}" as Long)
fun publicImage() {
        println("I'm starting.")
}
}

标签: javaspringspring-bootkotlinspring-el

解决方案


无需将其转换为 long,而是可以使用 fixedRateString。

@Scheduled(fixedRateString = "${fixrate}")

下面的代码在Java中工作

@Component
@PropertySource("file:/tmp/init.txt")
class CronSchedule {

    private static final Logger log = LoggerFactory.getLogger(CronSchedule.class);

    private static final SimpleDateFormat dateFormat = new SimpleDateFormat("HH:mm:ss");

    @Scheduled(fixedRateString = "${fixrate}")
    public void reportCurrentTime() {
        log.info("The time is now {}", dateFormat.format(new Date()));
    }
}

推荐阅读