Search code examples
spring-bootyamlconfigurationproperties

Injecting properties from application.yml to a map


I have my application.yml with different properties as shown below.

   lists:
      exampleList: [1,2,3]
      exampleString: abcde
      another:
         example1: exam1
         example2: exam2

And I'm binding these properties to a Spring Component using @ConfigurationProperties

@Data
@Component
@ConfigurationProperties
public class ExampleConfig {
    private Map<String,Object> lists;
}

I'll be injecting this component in a spring-boot controller and bind this config to a get configs endpoint /controller/config

When this endpoint is called, the expectation is to return

{
      "lists": {
         "exampleList": ["1", "2", "3"],
         "exampleString": "abcde"
         "another": {
            "example1": "exam1",
            "example2": "exam2"
         }
      }

   }

Instead it is returning the response as shown below

{
          "lists": {
             "exampleList": {
                 "0" : "1",
                 "1" : "2",
                 "2" : "3"
             }
             "exampleString": "abcde"
             "another": {
                "example1": "exam1",
                "example2": "exam2"
             }
          }

       }

List in yml is being mapped to an object in Map. How can we achieve the proper binding to the respective data types?

Appreciate your help!


Solution

  • There is a more sophisticated solution available. Instead of injecting all your configs to a Map you can have a simple Java DTO which represents the structure of your Configurations.

    Have your configs injected into Java DTO with @ConfigurationProperties and return JavaDTO from your controller endpoint.

    Refer to https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html#boot-features-external-config-typesafe-configuration-properties


    Spring boot actuator endpoint also has a specific endpoint called configprops which gives all of the config properties. However, if you want to use that you may need to do lots of customisations. For more info https://docs.spring.io/spring-boot/docs/current/reference/html/production-ready-endpoints.html