java - ConfigurationProperties 将属性名称与 yaml 文件中的数字绑定(bind)

标签 java spring spring-boot yaml

我是 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/

相关文章:

java - 使用 Spring Jdbc 模板面对嵌套 beans 查询

java - 如何为 JSP 配置 spring boot mvc 应用程序?

java - 有没有办法将 @Autowired 变量传递给 Spring Boot 应用程序中的其他类?

java - 如果应用程序有多个模块并且每个模块都是单独的项目,那么在 jboss 和 eclipse 中调试 java 应用程序的最佳方法是什么

java - 自 Spring Cloud Edgware.RC1 以来,spring.cloud.discovery.enabled 似乎无法正常工作

java - 如何在java中将字节重新解释为整数?

java - 无法写入 ID 为 0 的 JSON : Unable to find com. demo.model.Control;

java - 使用 spring @Scheduled 的问题

java - 为什么我在使用 JSch 时会看到乱七八糟的输出?

java - 使用java将字符串解析为日期