Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConfigurationProperties binding a property name with a number in from a yaml file

I'm new to Spring-Boot and have a problem binding a property value in the application.yml file to class annotated with @ConfigurationProperies.

In the application.yml:

aaa:
  what-1word-is: true

In the @ConfigurationProperties annotated class:

@Data
@Configuration
@ConfigurationProperties(prefix = "aaa")
public class Test
{
    private boolean what1WordIs;
}

I tried with different names for the property, but none of them works; what1WordIs is always false. Names I tried, what-1-word-is, what-1word-is, what1-word-is, what-1Word-is. Only what1-word-is works(set what1WordIs in configuration class to true)

Is Spring able to bind a property with a number in its name?

like image 512
ZTSean Avatar asked Jul 25 '18 19:07

ZTSean


1 Answers

It should work. I have tried and it works for me. Even for 'what-1-word-is'.

application.yml

aaa:
  what-1-word-is: true

Config.class

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);
  }
}

As result we can see :

CONFIG :: Config(what1WordIs=true)

I think you faced this issue because you used @Configuration annotation instead of @Component.

BTW: Spring allows us to use different property names in config file. I've tried all options you've mentioned and it works. (More: https://docs.spring.io/spring-boot/docs/current/reference/html/spring-boot-features.html#boot-features-external-config-relaxed-binding )

BTW2: If you want take a look which properties Spring expects you can add into dependency this:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

It will generate spring-configuration-metadata.json in /target/classes/META-INF directory where all properties are described. Example:

{
  "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": []
}

Moreover, an IDE will be able to autocomplete for you :)

BTW3: Please check, that you use @Data from Lombok library.

I hope it's still actual :)

like image 73
Vladyslav Diachenko Avatar answered Sep 30 '22 09:09

Vladyslav Diachenko