如何在Azure App Configuration中存储Map类型值并在Spring Boot中读取
实现方案
步骤1:在Azure App Configuration中存储数据
Azure App Configuration的值默认支持字符串类型,你可以把要存储的Map序列化为合法JSON字符串作为值存入:
- 键名按你的业务需求定义,比如
app.config.custom-map - 对应的值输入标准JSON格式字符串(注意你示例中的集合需要调整为JSON数组格式,用
[]包裹):
{"1": [1,2,3], "2": [1,4]}
步骤2:Spring Boot项目配置读取
首先确保项目已经引入Azure App Configuration对应的Spring Boot Starter依赖,之后通过配置属性绑定即可直接读取为Map<Integer, List
- 编写配置属性类
import org.springframework.boot.context.properties.ConfigurationProperties; import java.util.List; import java.util.Map; @ConfigurationProperties(prefix = "app.config") public class CustomConfigProperties { private Map<Integer, List<Integer>> customMap; // 对应getter、setter方法 public Map<Integer, List<Integer>> getCustomMap() { return customMap; } public void setCustomMap(Map<Integer, List<Integer>> customMap) { this.customMap = customMap; } }
- 在启动类上开启配置属性绑定
import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.context.properties.EnableConfigurationProperties; @SpringBootApplication @EnableConfigurationProperties(CustomConfigProperties.class) public class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } }
- 业务代码中注入使用
@Autowired private CustomConfigProperties customConfigProperties; // 直接调用即可拿到对应结构的配置 Map<Integer, List<Integer>> configMap = customConfigProperties.getCustomMap();
补充说明
- 存储时必须保证JSON格式合法,否则Spring Boot绑定参数时会抛出类型转换异常
- 如果你不想单独写配置类,也可以用SpEL表达式结合
@Value直接读取,写法为@Value("#{${app.config.custom-map}}") private Map<Integer, List<Integer>> customMap;,不过更推荐用@ConfigurationProperties的方式,类型校验和配置提示的友好度更高
内容的提问来源于stack exchange,提问作者suraj jain
相关产品推荐
相关产品推荐

