Spring Boot-从application.yml

时间:2018-12-07 15:13:17

标签: java spring spring-boot

我引用Spring Boot - inject map from application.yml来从application.yml文件中注入地图

我的application.yml代码段如下

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

属性文件如下所示

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

}

上面给出的代码有效。当将 pairMap 设置为静态时,不会从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:问题仅在注入map时出现,而在注入字符串时不存在。为什么会这样?

即在以下配置中进行以下字符串注入,但不会进行地图注入

easy.app.key1: 'abc'

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

如下所示的属性文件

@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 个答案:

答案 0 :(得分:0)

解决此问题:

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

}