我是 Spring-Boot 的新手,在将 application.yml 文件中的属性值绑定(bind)到用 @ConfigurationProperies
注释的类时遇到问题。
在application.yml中:
aaa:
what-1word-is: true
在@ConfigurationProperties
注解类中:
@Data
@Configuration
@ConfigurationProperties(prefix = "aaa")
public class Test
{
private boolean what1WordIs;
}
我尝试为该属性使用不同的名称,
但它们都不起作用;
what1WordIs
始终为 false
。
我试过的名字,
what-1-word-is
,
what-1word-is
,
what1-word-is
,
what-1Word-is
。
只有 what1-word-is
有效(将配置类中的 what1WordIs
设置为 true
)
Spring 是否能够绑定(bind)名称中带有数字的属性?
最佳答案
它应该可以工作。 我试过了,它对我有用。即使对于“what-1-word-is”也是如此。
应用程序.yml
aaa:
what-1-word-is: true
配置类
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
@Component
@ConfigurationProperties(prefix = "aaa")
@Data
public class Config {
private boolean what1WordIs;
@PostConstruct
public void init(){
System.out.println("CONFIG :: "+this);
}
}
结果我们可以看到:
CONFIG :: Config(what1WordIs=true)
我认为您遇到这个问题是因为您使用了@Configuration 注释而不是@Component。
顺便说一句:Spring 允许我们在配置文件中使用不同的属性名称。我已经尝试了您提到的所有选项并且有效。 (更多:https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-relaxed-binding)
顺便说一句:如果你想看看 Spring 期望哪些属性,你可以将其添加到依赖项中:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
它将在描述所有属性的 /target/classes/META-INF
目录中生成 spring-configuration-metadata.json
。
示例:
{
"groups": [
{
"name": "aaa",
"type": "com.supra89kren.test_spring.configurtion.Config",
"sourceType": "com.supra89kren.test_spring.configurtion.Config"
}
],
"properties": [
{
"name": "aaa.what1-word-is",
"type": "java.lang.Boolean",
"sourceType": "com.supra89kren.test_spring.configurtion.Config",
"defaultValue": false
}
],
"hints": []
}
此外,IDE 将能够为您自动完成 :)
顺便说一句:请检查您是否使用了 Lombok 库中的@Data。
我希望它仍然是真实的:)
关于java - ConfigurationProperties 将属性名称与 yaml 文件中的数字绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51526094/