Home > OS >  Spring Boot inject List of Maps from application.yml
Spring Boot inject List of Maps from application.yml

Time:12-08

I am trying to inject List of Maps from Spring Boot config but getting an empty List. How to inject this correctly?

cacheConfigs:
  - cacheOne:
       test: test1
  - cacheTwo:
       test: test2
  - cacheThree:
       test: test3
  - cacheFor:
       test: test4
@ConfigurationProperties(prefix = "cacheConfigs")
public List<Map<String, String>> getCacheConfigs() {
    return new ArrayList<>();
}

CodePudding user response:

This was a "new" for me. I got this working by making cacheConfigs one level deeper and the used the new top level name as the @ConfigurationProperties param. Like this:

cache-configs-map:
  cacheConfigs: 
    - cacheOne:
        test: test1
    - cacheTwo:
        test: test2
    - cacheThree:
        test: test3
    - cacheFor:
        test: test4

Now, your configuration class looks like this:

@Configuration
public class Config{
    @NoArgsConstructor @AllArgsConstructor( staticName = "of" )
    @Getter @Setter
    public static class C{
        private List<Map<String, String>> cacheConfigs;
    }
    
    @Bean
    @ConfigurationProperties(prefix = "cache-configs-map")
    public C getC() {
        return new C();
    }
}
  • Related