Spring Boot通过Nacos动态获取yaml配置的List数组对象并映射
方案一
需求简介
- 在yml文件动态配置项目名称与项目ID(动态配置通过nacos实现)
- 因为列表数量很少,又会改动,又不想存数据库单独建个表维护,故通过配置文件的项目列表信息
application.yml 配置
新增/删除/更改 list 即可
projects:
list:
- name: project_one
projectId: project_01
- name: project_two
projectId: project_02
配置类
@RefreshScope
@Configuration
@ConfigurationProperties(prefix = "projects")
public class Projects {
public static List<Map<String, String>> list; //static 才能拿配置值
public static List<Map<String, String>> getList() {
return list;
}
public void setList(List<Map<String, String>> list) {
Projects.list = list;
}
}
REST接口
@GetMapping("/projects")
public Result<Object> projectList() {
List<Map<String, String>> list = Projects.getMap();
return Result.ok(list);
}
缺陷:不能动态刷新
方案二(终极方案)
alipay:
custom:
productList:
- productId: alipay_test1
productType: offline
merchantIds: 10000001,10000002
partnerId: '2088******'
commissionFlag: test1
signType: MD5
signKey: ******
callbackKey: ******
- productId: alipay_test2
productType: offline
merchantIds: 10000005,10000006
partnerId: '2088******'
commissionFlag: test2
signType: RSA
signKey: ******
callbackKey: ******
- productId: alipay_test3
productType: online
merchantIds: 10000007,10000008
partnerId: '2088******'
commissionFlag: test3
signType: RSA
signKey: ******
callbackKey: ******
@Configuration
@RefreshScope
public class AlipayCustomConfig {
@Bean
@ConfigurationProperties(prefix = "alipay.custom.products")
public List<Map<String, String>> products() {
// old key still exist when delete this key on nacos
return new ArrayList<>();
}
}
@Slf4j
@RestController
public class TestController {
@Autowired
private AlipayCustomConfig alipayCustomConfig;
@GetMapping("/test")
@ResponseBody
public String getKey() {
return JsonUtil.obj2Str(alipayCustomConfig.products());
}
}
版权声明:
作者:Joe.Ye
链接:https://www.appblog.cn/index.php/2023/04/01/spring-boot-dynamically-obtains-yaml-configured-list-array-object-through-nacos/
来源:APP全栈技术分享
文章版权归作者所有,未经允许请勿转载。
THE END
0
二维码
打赏
海报
Spring Boot通过Nacos动态获取yaml配置的List数组对象并映射
方案一
需求简介
在yml文件动态配置项目名称与项目ID(动态配置通过nacos实现)
因为列表数量很少,又会改动,又不想存数据库单独建个表维护,故通过配置文件……
文章目录
关闭
共有 0 条评论