Spring Boot 无法解析在@Configuration类中注入的YML @Value

rsl1atfo  于 2024-01-06  发布在  Spring
关注(0)|答案(2)|浏览(154)

正如this answer所建议的那样,这应该可以正常工作。

  1. # application-dev.yml
  2. gateway:
  3. publicEndpoints:
  4. - /api/v1/example,
  5. - /api/v1/another-example

个字符
但是,我得到了

  1. Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'gateway.publicEndpoints' in value "${gateway.publicEndpoints}"


我尝试删除逗号(s)在yml文件,但得到相同的结果
我也试

  1. @Configuration
  2. @EnableWebFluxSecurity
  3. public class SecurityConfig {
  4. @Value("${gateway.publicEndpoints}")
  5. private String[] publicEndpoints;


得到了同样的例外
配置文件正确(dev):

  1. The following 1 profile is active: "dev"


Salvatore Bernardo提出的使用@ConfigurationProperties的建议确实有帮助,但是我仍然很好奇为什么我不能在代码中成功地使用@Value
Salvatore还假设,这可能是由于@Value似乎不支持yml(文档does not corroborate的想法)
另一个家伙在SO had a similar problem,它似乎是由于错误的识别(我的识别是好的)
那是什么原因造成的呢?
Spring Boot 3.1.4

rbl8hiat

rbl8hiat1#

对于复杂的结构(列表,Map)使用ConfigurationProperties。我在这里复制了https://github.com/sbernardo/spring-issues-examples/tree/main/sof-questions-77691200您的问题,并使用ConfigurationProperties修复
这个问题类似于Can't get Java see my custom YAML property in a Spring Boot app
@Value很适合用于简单值,例如String值。
希望这会有所帮助:)

siotufzp

siotufzp2#

似乎是 *.yml格式的某种问题。如果你用逗号拼写参数,像这样:

  1. gateway:
  2. publicEndpoints: /api/v1/example, /api/v1/another-example

字符串
一切正常
尽管文档中说列表是在 *.yml中使用“破折号和空格”here生成的,

相关问题