简体   繁体   English

Spring Boot-从application.yml注入静态映射

[英]Spring Boot - inject static map from application.yml

I refered Spring Boot - inject map from application.yml for injecting map from application.yml file 我引用了Spring Boot- 从application.yml注入映射以从application.yml文件注入映射

My application.yml snippet is below 我的application.yml片段如下

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. 上面给出的代码有效,当' pairMap '设置为static时,不会从application.yml文件中读取Map

@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. PS:问题仅在注入map时出现,而在注入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;
}

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});
     }
  }

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM