6

I have injected properties from the map read from some .yaml in Spring Boot application the following way:

@Value("#{${app.map}}")
private Map<String, String> indexesMap = new HashMap<>();

But neither

app:
    map: {Countries: 'countries.xlsx', CurrencyRates: 'rates.xlsx'} 
    //note values in single quotes  

nor
app:
    map: {Countries: "countries.xlsx", CurrencyRates: "rates.xlsx"}

(as explained at https://www.baeldung.com/spring-value-annotation)

nor

app:
    map:
      "[Countries]": countries.xslx
      "[CurrencyRates]": rates.xlsx

(as suggested at https://stackoverflow.com/a/51751123/2566304)

works - I keep getting the message 'Injection of autowired dependencies failed; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder'

At the same time this works:

@Value("#{{Countries: 'countries.xlsx', CurrencyRates: 'rates.xlsx'}}")
private Map<String, String> indexesMap = new HashMap<>();

But I'd like to externalize properties

Anthon
  • 69,918
  • 32
  • 186
  • 246

1 Answers1

9

Use @ConfigurationProperties, as suggested in one of the answers from the question you linked:

@Bean(name="AppProps")
@ConfigurationProperties(prefix="app.map")
public Map<String, String> appProps() {
    return new HashMap();
}

and then

@Autowired
@Qualifier("AppProps")
private Map<String, String> props;

would work with the config

app:
  map:
    Countries: 'countries.xlsx'
    CurrencyRates: 'rates.xlsx'

EDIT: @Value annotation works as well, but you have to treat it as a String in YAML:

@Value("#{${app.map}}")
private Map<String, String> props;

and

app:
  map: "{Countries: 'countries.xlsx', CurrencyRates: 'rates.xlsx'}"

Note the quotes around the map value. Apparently Spring parses it out of a String in this case.

Alex Savitsky
  • 2,306
  • 5
  • 24
  • 30