Search code examples
javaspringspring-bootrecord

How to create Record from application.yaml in Spring boot


We are creating APIs using spring boot and there are some configurations that would supply as env in the docker container ad below:

config:
   host: ${HOST}
   apiKey: ${API_KEY}

I need this host and API key in my service class to make an external API call.

Is there any way to create Record class directly from application.yaml as below in Spring boot?

public record Config(String host, String apiKey){}

Solution

  • On Main class add @ConfigurationPropertiesScan

    Create class like this and this should work

    @ConfigurationProperties(value = "config")
    public record Config(String host, String apiKey) { }
    

    Or if you want also default settings

    @ConfigurationProperties(value = "config")
    public record Config(String host, String apiKey) {
    
        @ConstructorBinding
        public Config(String host, String apiKey) {
            this.host = Optional.ofNullable(host).orElse("localhost");
            this.apiKey = Optional.ofNullable(apiKey).orElse("secret");
        }
    }