Spring @Value 注入List和Map

Spring @Value 注入List和Map

EL表达式+JSON写法

  • .java
@Value("#{'${scio.cloud.list}'.split(',')}")
private List list;
 
@Value("#{${scio.cloud.maps}}")  
private Map maps;
  • .yml
scio.cloud.list: topic1,topic2,topic3
scio.cloud.maps: "{key1: 'value1', key2: 'value2'}"

yml常规写法

  • .yml
scio:
  cloud
    list: 
      - topic1
      - topic2
      - topic3
scio:
  cloud:
    maps: 
      key1: 'value1'
      key2: 'value2'

或者

scio:
  cloud
    list: 
      - topic1
      - topic2
      - topic3
scio.cloud.maps[key1]: 'value1'
scio.cloud.maps[key2]: 'value2'
  • .java
@EnableConfigurationProperties
@Configuration
@ConfigurationProperties(prefix = "scio.cloud")
publci class ScioCloudConfig{
    
    private List list;
    
    private Map maps;
    
    public void setList(List list){
        this.list = list;
    }
    
    public void setMaps(Map maps){
        this.maps = maps;
    }
    
    
}

重点重点

使用了@ConfigurationProperties需要对属性写setter方法。

你可能感兴趣的:(Spring @Value 注入List和Map)