SpringBoot实现从配置中注入多级Map到bean中

假设要搞一个2级map: type -> level -> score

先看配置:

xxxx.old.type2Level2ScoreMap:
  type_1.level2ScoreMap.level_1: 1
  type_1.level2ScoreMap.level_2: 2
  type_2.level2ScoreMap.level_1: 1
  type_3.level2ScoreMap.level_1: 1

首先搞定2个数据结构,注意一定要字段名对应,层级对应:

public class Type2Level2Score {

    private Map<String, Level2Score> type2Level2ScoreMap;

    public Map<String, Level2Score> getType2Level2ScoreMap() {
        return type2Level2ScoreMap;
    }

    public void setType2Level2ScoreMap(Map<String, Level2Score> type2Level2ScoreMap) {
        this.type2Level2ScoreMap = type2Level2ScoreMap;
    }

}
public class Level2Score {

    private Map<String, Integer> level2ScoreMap;

    public Map<String, Integer> getLevel2ScoreMap() {
        return level2ScoreMap;
    }

    public void setLevel2ScoreMap(Map<String, Integer> level2ScoreMap) {
        this.level2ScoreMap = level2ScoreMap;
    }
}

然后是配置

@Configuration
public class Type2Level2ScoreConfiguration {

    @Bean
    @ConfigurationProperties(prefix = "xxxx.old")
    public Type2Level2Score oldConfig() {
        return new Type2Level2Score();
    }

}

在需要的地方,直接使用即可

@Autowired
@Qualifier("oldConfig")
private Type2Level2Score oldConfig;

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *