如何将 yaml 与 Spring Boot @Value 一起使用,无法解析值“${secret.jwt}”中的占位符“secret.jwt”

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

安全.yml

路径:src/main/resources/security.yml

## Secret Key

## 1
secret-jwt: my-jwt-secret
## 2
secret.jwt: my-jwt-secret
## 3
secret:
  jwt: my-jwt-secret
  cookey: my-cookey-secret

issuer: https://my-test-project.com

使用yml的类

@PropertySource("classpath:security.yml")
@Service
@Transactional(readOnly = true)
class TokenProvider(
    @Value("\${secret.jwt}") private val jwtSecretKey: String,

    @Value("\${issuer}") private val issuer: String,
    // ...Several Constuctor Injected Services
) {
    // ...
}

发生异常

Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'secret.jwt' in value "${secret.jwt}"
    at org.springframework.util.PropertyPlaceholderHelper.parseStringValue(PropertyPlaceholderHelper.java:180)
    at org.springframework.util.PropertyPlaceholderHelper.replacePlaceholders(PropertyPlaceholderHelper.java:126)
    at org.springframework.core.env.AbstractPropertyResolver.doResolvePlaceholders(AbstractPropertyResolver.java:239)
    at org.springframework.core.env.AbstractPropertyResolver.resolveRequiredPlaceholders(AbstractPropertyResolver.java:210)
    at org.springframework.context.support.PropertySourcesPlaceholderConfigurer.lambda$processProperties$0(PropertySourcesPlaceholderConfigurer.java:200)
    at org.springframework.beans.factory.support.AbstractBeanFactory.resolveEmbeddedValue(AbstractBeanFactory.java:921)

依赖关系总结

Using Kotlin Gradle DSL

jvm version : corretto-21
Kotlin version : 1.9.22
gradle : v8.4
Spring boot starter, web, security : 3.2.1

#1 - 与

@Value("\${secret-jwt}") private val jwtSecretKey: String,
一起工作 #2 - 工作。 #3 - 不工作。

所以,

@PropertySource
@Value
效果很好。它可以很好地加载顶级变量,因此
@PropertySource
注解或 YAML 路径清晰。而且很明显我使用了正确的
@Value
注释,它来自 Spring(不是 Lombok)

尝试了 Gradle clean/build、Invalidate IntelliJ IDEA Caches 多次但没有任何变化,所以 IDEA 或 Gradle 不是问题。

有谁知道为什么我写的嵌套 yaml(#3) 不起作用?我是否必须创建另一个 POJO 进行配置?我看到了 YAML 教程、YAML Linter、GPT、Spring Docs、Google 但没有任何线索

spring-boot kotlin yaml
© www.soinside.com 2019 - 2024. All rights reserved.