SpringBoot读取yml文件,获取List数组和Map集合

一、基础知识

前提:了解java的yml文件的编写格式。确保自己配置好springboot环境,可以启动。

二、场景

在开发中,先在yml文件中配置一些我需要监测的 url 和出现异常的时候发送给企业微信的工作群中的机器人码,前期通过这里先配置,以后改到页面中配置~

三、例子demo

3.1 获取List集合

        配置yml文件,一个 “ - ” 代表一组,整体是一个List。

sem:
  bots:
    - name: Bot1
      type: oneMinuteCheck
      url: https://xxxxx/open-api/v1/xxxx
      wxRobotIds:
        - c46bf5eb-0805-4eae
        - c46bf5eb-0805-4eae    
    - name: Bot2
      type: fiveMinuteCheck
      url: https://xxxxxx/toutiaolive/open-api/v1/xxxxx
      wxRobotIds:
        - c46bf5eb-0805-4eae
        - c46bf5eb-0805-4eae

       实体类 ,注意和yml的字段保持一致,yml是name,实体类也是name。

@Data //lombok注解,提供get,set等方法
public class BotConfig {
    private String name;
    private String type;
    private String url;
    private List<String> wxRobotIds;
}

    配置类,加上@ConfigurationProperties(prefix = "sem")配置注解,注意配置类的路径和yml文件中要保持一致,加上集合的名称bots,这里对应yml的 sem.bots

@Data
@Component
@ConfigurationProperties(prefix = "sem")
public class BotConfigConfiguration {
    private List<BotConfig> bots;
} 

 获取配置信息

@AllArgsConstructor
public class BotConfigServiceImpl {

    //自动注入
    @Autowired
    private BotConfigConfiguration botConfigConfiguration;

    //写个方法返回获取的List
    public List<BotConfig> getBotConfig() {
        List<BotConfig> botConfigList = botConfigConfiguration.getBots();
        return botConfigList;
    }

}

 接口请求获取一下配置信息,获取成功,或者直接在控制台打印也可以。

@Slf4j
@RequestMapping("/v1/test")
@RestController
public class OpenTestController {

    @Autowired
    private BotConfigServiceImpl botConfigService;

    //测试获取url
    @GetMapping(value = "/test/getBotConfig")
    public List<BotConfig> getBotConfig() {

        return botConfigService.getBotConfig();
    }

}

  返回结果,能够获取到List集合

3.2 获取Map集合

    配置yml文件, “4305286041189348”对应 map 的 key,后面对应values。

bots:
  config:
    4305286041189348:
      name: Bot4
      type: oneHourCheck
      url: https://xxxxxx/open-api/v1/monitor/test
      wxRobotIds:
        - c46bf5eb-0805-4eae
        - c46bf5eb-0805-4eae
    1709044407825416:
      name: 1709044407825416
      type: 4305286041189348
      url: https://xxxxxxx/api/open-api/v1/monitor/test
      wxRobotIds:
        - c46bf5eb-0805-4eae
        - c46bf5eb-0805-4eae

   配置类,对应yml的路径,配置类实体对应yml的结构即可。

@Data
@Component
@ConfigurationProperties(prefix = "bots")
public class BotConfigConfiguration {

    //对应配置的结构,BotConfig同上面List的同一个实体类
    private Map<String, BotConfig> config;
    
} 

  自己写代码测试一下结果即可~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值