1
votes

I refered Spring Boot - inject map from application.yml for injecting map from application.yml file

My application.yml snippet is below

easy.app.pairMap:
    test1: 'value1' 
    test2: 'value2'

Properties file is like below

@Component
@Configuration
@ConfigurationProperties("easy.app")
@EnableConfigurationProperties
public class TestProperties {



private Map<String, String> pairMap= new HashMap<String, String>();

public void setPairMap(Map<String, String> pairMap) {
    this.pairMap= pairMap;
}

}

The above given code works .Map is not read from application.yml file when the 'pairMap' is set as static as below.

@Component
@Configuration
@ConfigurationProperties("easy.app")
@EnableConfigurationProperties
public class TestProperties {



private static Map<String, String> pairMap= new HashMap<String, String>();

public static void setPairMap(Map<String, String> pairMap) {
    TestProperties .pairMap= pairMap;
}

}

PS : The issue is only when injecting map , but not on injecting string. Why is this behaviour?

ie the following injection of string in the following configuration works , but not the map injection

easy.app.key1: 'abc'

easy.app.pairMap:
     test1: 'value1' 
     test2: 'value2'

Properties file like below

@Component
@Configuration
@ConfigurationProperties("easy.app")
@EnableConfigurationProperties
public class TestProperties {



private Map<String, String> pairMap= new HashMap<String, String>();

private static String key1;

public static void setPairMap(Map<String, String> pairMap) {
    this.pairMap= pairMap;
}

public static void setKey1(String key1) {
    TestProperties.key1= key1;
}



public String getKey1(){
    return key1;
}
1
Possible duplicate of @autowired in static classes. I think that thread will show you the way.Robert Moskal
What if I remove the @Component tag?Abhi
Answer is: here, but don't use static explains: hereAndrii Vdovychenko
why do you want to make it static @AbhiDeadpool
some of the fields including map in myclass need to be static and the others need to be non staticAbhi

1 Answers

0
votes

Fix with this:

easy:
  app:
    pairMap:
      test1: value1
      test2: value2

 @CompileStatic
 @Component
 @EnableConfigurationProperties
 class ConfigHolder {

   @Value(value = '${easy.app.pairMap.test1}')
   String test1Valse;

   @Value(value = '${easy.app.pairMap.test2}')
   String test2Valse;
 }



@CompileStatic
@Configuration
@EnableConfigurationProperties
public class TestProperties {

  @Autowired
  ConfigHolder configHolder;



  private Map<String, String> pairMap= new HashMap<String, String>();


  public void setPairMap(Map<String, String> pairMap) {
     if(pairMap != null && !pairMap.isNotEmpty()) {
        this.pairMap = pairMap;
     } else {
        this.pairMap.put("test 1", ${configHolder.test1Valse});
        this.pairMap.put("test 2", ${configHolder.test2Valse});
     }
  }

}