Home > Blockchain >  Spring Boot: Map a map from application.yaml to a map with @Value annotation
Spring Boot: Map a map from application.yaml to a map with @Value annotation

Time:04-29

I have a yaml file application.yaml in src/main/resources/:

it:
  env:
    key1: 'val1'
    key2: 'val2'

now I want the values in it.env mapped to a map in java. And I tried the following approaches:

@SpringBootTest
public class Test {
   
    @Value("${it.env.key1:'unknown'}")
    private String key1;

    @Value("${it.env}")
    private Map<String, String> envConfig;

    @Value("#{${it.env}}")
    private Map<String, String> envConfig;

}

But all I get is an error: @Value("${it.env}") gives me:

Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert value of type 'java.lang.String' to required type 'java.util.Map'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'java.util.Map': no matching editors or conversion strategy found

@Value("#{${it.env}}") gives me:

Caused by: org.springframework.beans.factory.BeanExpressionException: Expression parsing failed; nested exception is org.springframework.expression.spel.SpelParseException: EL1041E: After parsing a valid expression, there is still more data in the expression: 'lcurly({)'

Any ideas why this isn't working?

CodePudding user response:

The following yaml format (1) using the @Value parsing structure (2) is the way to go

(1)

it:
  env:
    key1: 'value1'
    key2: 'value2'

(2)

@Value("#{${it.env}}")
private Map<String, String> envConfig;

My guess is that the resolution of ${KEY1:val1} is not 'value1' and same thing with the resolution of ${KEY2:val2}

CodePudding user response:

It works if you don't use @Value but use @ConfigurationProperties. For that you need add a new class.

@Component
@ConfigurationProperties(prefix = "it")
public class TestEnvProperties {

    Map<String, String> env;

    // Getters and setter...

}
  • Related