Spring:如何在注释中从配置文件注入整数和长值

问题描述 投票:0回答:2

我正在努力使用 spring 项目中的配置变量来注入注释中除 String 之外的值。有办法注射吗?
注释需要 Integer 和 long 值,但从 application.yml 注入时,它被视为 String。

请参阅下面的示例:

@Scheduled(fixedRate = "${scheduler.fixedrate:10}")
public void init(){}

错误是:

不兼容的类型。找到:'java.lang.String',必需:'long'

有什么解决办法吗?

java spring annotations
2个回答
0
投票

@Scheduled
注释还有一个
fixedRateString
属性:

    /**
     * Execute the annotated method with a fixed period between invocations.
     * <p>The time unit is milliseconds by default but can be overridden via
     * {@link #timeUnit}.
     * @return the period as a String value &mdash; for example, a placeholder
     * or a {@link java.time.Duration#parse java.time.Duration} compliant value
     * @since 3.2.2
     */
    String fixedRateString() default "";

0
投票

我认为没有办法做到这一点。由于它必须是编译时常量,因此在应用程序运行并且 spring 已确定属性的实际值之前,无法将字符串解析为配置中的实际值。

我认为这也是为什么你的例子也存在

fixedRateString
的原因。

© www.soinside.com 2019 - 2024. All rights reserved.