在注释参数/参数中使用@ConfigurationProperties?(必须是编译时常量)

stk*_*stk 5 kotlin micronaut

I\xc2\xb4m 尝试在注释中使用配置,如下所示:

\n
@ConfigurationProperties("scheduling")\ninterface SchedulingConfiguration {\n    val initialDelay: String\n    val fixedDelay: String\n}\n
Run Code Online (Sandbox Code Playgroud)\n
\n
@Singleton\nclass Worker(\n    private val configuration: SchedulingConfiguration,\n) {\n    private val log = LoggerFactory.getLogger(javaClass)\n\n    @Scheduled(initialDelay = configuration.initialDelay, fixedDelay = configuration.fixedDelay)\n    fun fetchQueueEntry() {\n        log.info("Fetching entry")\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

I\xc2\xb4m 收到警告An annotation argument must be a compile-time constant

\n

有什么方法可以让它与 Micronaut 一起工作吗?

\n

stk*_*stk 2

我通过浏览 Micronaut 文档并意外地偶然发现了 Property Placeholders 来设法让它运行。即使感觉不是“最佳”,这也会很好地工作。

\n
@Singleton\nclass Worker {\n    private val log = LoggerFactory.getLogger(javaClass)\n\n    @Scheduled(\n        initialDelay = "\\${scheduling.initialDelay}",\n        fixedDelay = "\\${scheduling.fixedDelay}"\n    )    \n    fun fetchQueueEntry() {\n        log.info("Fetching entry")\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n

xc2xb4s 还可以定义默认值,如果配置文件或环境变量中不存在键,则将使用这些默认值:

\n
    @Scheduled(\n        initialDelay = "\\${scheduling.initialDelay:0s}",\n        fixedDelay = "\\${scheduling.fixedDelay:10s}"\n    )    \n
Run Code Online (Sandbox Code Playgroud)\n

如果没有默认值并且没有使用属性占位符的配置,则会在运行时抛出异常,并且应用程序将关闭。

\n