首页 > 解决方案 > 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-iswhat-1Word-iswhat1-word-iswhat1WordIstrue

Spring 是否能够绑定名称中带有数字的属性?

标签: javaspringspring-bootyaml

解决方案


它应该工作。我已经尝试过了,它对我有用。即使是“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。

我希望它仍然是真实的:)


推荐阅读