1

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){}
Nitin
  • 2,701
  • 2
  • 30
  • 60
  • I think this is what you are looking for, not sure if it works on a record or not: https://stackoverflow.com/questions/30528255/how-to-access-a-value-defined-in-the-application-properties-file-in-spring-boot – Nick Aug 23 '23 at 07:47
  • 1
    [configurationproperties-with-records](https://stackoverflow.com/questions/66696828/how-to-use-configurationproperties-with-records) – Andrei Lisa Aug 23 '23 at 07:52

1 Answers1

2

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");
    }
}
saw1k
  • 131
  • 1
  • 2