如何使用大写环境变量设置Spring camel case属性?

And*_*inn 9 spring spring-boot

我有一些代码在我的Spring应用程序中加载一个值:

@Component
public class MyElasticRestService {
    @Value("${elasticApi.baseURL}")
    private String elasticApiBaseUrl;
Run Code Online (Sandbox Code Playgroud)

根据Spring文档,我应该能够使用来自大写环境变量(例如ELASTIC_API_BASE_URL或)的宽松绑定ELASTICAPI_BASEURL.但我很困惑哪个是正确的.两者似乎都不起作用所以我想知道如何调试实际拾取的内容.

我已经加载了Spring Boot Actuator来查看configprops端点.但它的elasticApi前缀没有任何内容.

正确的环境变量应该是什么?如何才能看到它如何被应用程序翻译和拾取?

jos*_*ste 6

@Value注释不支持轻松绑定.因此,您可以使用带注释的类@ConfigurationProperties或使用a RelaxedPropertyResolver来从环境中获取值.

  • 当我读到你的答案时,我无法相信这一点.不过你是对的.文档实际上表明它只适用于@ConfigurationProperties bean,如果你仔细阅读:https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot -features-外部配置,轻松结合 (3认同)
  • 显然,宽松的绑定现在也可以用于“@Value”。不过,您可能必须在“@Value”中使用短横线大小写。 (2认同)

san*_*o21 5

根据https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-vs-value,现在很可能简单只要@Value 您使用 kebab-case(全部小写,带破折号)作为名称,例如 @Value("config.refresh-rate")