Spring Boot通过Nacos动态获取yaml配置的List数组对象并映射

方案一

需求简介

  1. 在yml文件动态配置项目名称与项目ID(动态配置通过nacos实现)
  2. 因为列表数量很少,又会改动,又不想存数据库单独建个表维护,故通过配置文件的项目列表信息

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());
    }
}
上一篇 整合Nacos和Druid(password使用密文)出现新建连接被拒绝情况
下一篇 Spring Boot集成Nacos动态刷新数据源
目录
文章列表
1 Spring Boot同一应用启动两个ElasticJob其中一个未启动问题
Spring Boot同一应用启动两个ElasticJob其中一个未启动问题
2
SpringBoot 2.0集成百度UidGenerator
SpringBoot 2.0集成百度UidGenerator
3
Android.mk中打印输出信息
Android.mk中打印输出信息
4
Android Studio中ButterKnife安装使用
Android Studio中ButterKnife安装使用
5
Hexo标题特殊符号引发错误(冒号、引号、美元符、连字符)
Hexo标题特殊符号引发错误(冒号、引号、美元符、连字符)
最新评论
一位WordPress评论者
一位WordPress评论者
2月12日
您好,这是一条评论。若需要审核、编辑或删除评论,请访问仪表盘的评论界面。评论者头像来自 Gravatar。