如何从 application.yml 中读取 Long 类型的值

How to read a value of type Long from a application.yml

我正在使用 redis 缓存。我的代码中有

时间是硬编码的地方

@RedisHash(timeToLive=60)

在 applications.yml 文件中我想添加以下内容

throttle: 
  cache: 
    rate: 60 

所以我可以有以下

@RedisHash(timeToLive="${throttle.cache.rate}")

但是由于类型不匹配无法从字符串转换为长整型而失败。所以我尝试了

@RedisHash(timeToLive="#{new Long(}'${throttle.cache.rate}')")

但仍然失败,类型不匹配无法从 String 转换为 Long。

基本上,那是不可能的。为什么?因为注释的值必须是编译时常量。编译器在编译时只知道你将 String 传递给只接受 long.

的 属性

当您 运行 您的 Spring 应用程序时,它只会是 long,但为时已晚,因为编译器不知道。