java - ConfigurationProperties 将属性名称与 yaml 文件中的数字绑定
问题描述
我是 Spring-Boot 的新手,在将 application.yml 文件中的属性值绑定到用@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 是否能够绑定名称中带有数字的属性?
解决方案
它应该工作。我已经尝试过了,它对我有用。即使是“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 )
BTW2:如果你想看看 Spring 期望哪些属性可以添加到依赖项中:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
它将在描述所有属性的目录中spring-configuration-metadata.json
生成。/target/classes/META-INF
例子:
{
"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 将能够为您自动完成 :)
BTW3:请检查您是否使用 Lombok 库中的 @Data。
我希望它仍然是真实的:)
推荐阅读
- github-actions - 是否可以在 GitHub Actions 中定义主机映射?
- javascript - 3级后不要使用node js读取目录
- c# - 在不使用 OLEDB 的情况下将 Excel 转换为 JSON
- rust - 如何将多个字节“读取”到“Vec”中?
- c++ - 以下二叉搜索树节点删除方法如何工作?
- python - 如何将创建的 csv 保存到 cloudinary 云中?
- python - 如何查找存在文件夹的文件夹
- azure - 如何以编程方式获取 Azure 订阅费用
- antd - [antd]如何在选择要上传的文件窗口跳出之前进行检查
- python - 如何从 Odoo 13 中邮件中的 url/按钮批准休假(休假模块)