SpringBoot yaml配置List 数组对象并映射

简介

最近有这样一个需求

1. 在yml文件动态配置项目名称与ID (动态配置通过nacos实现,这里不讲述)

2. 因为列表数量很少,又会改动,又不想存数据库单独建个表维护,故通过配置文件的项目列表信息

application.yml 配置

新增/删除/更改 list 即可

projects:
  list:
    - name: project_one
      projectId: project_id_111111
    - name: project_two
      projectId: project_id_222222
    - name: your_name
      projectId: your_id

 配置类

@ConfigurationProperties(prefix = "projects")

@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;
    }
}

接口

@GetMapping("/projects")
public Result<Object> projectList() {
    List<Map<String, String>> list = Projects.getList(); 

return Result.ok(list);
}

 响应效果

{
  "success": true,
  "message": "操作成功!",
  "code": 200,
  "result": [
    {
      "name": "project_one",
      "projectId": "project_id_111111"
    },
    {
      "projectId": "project_id_222222",
      "name": "project_two"
    },
    {
      "projectId": "your_id",
      "name": "your_name"
    }
  ],
  "timestamp": 1601342384895
}

 

posted @ 2020-09-28 17:39  levi125  阅读(29902)  评论(2编辑  收藏  举报