Springboot读取配置文件List类型数据

本文介绍如何使用Spring Boot读取YAML配置文件中的List类型数据,并通过实体类进行映射。包括配置文件示例、自定义实体类及如何在业务逻辑中注入和使用这些配置。

包装实体类

一、aplication.yml

custom:
  whiteUrl:
    - /1/1
    - /2/2

二、添加配置文件 - CustomConfig

@Configuration
//@PropertySource("custom.yml")
@ConfigurationProperties(prefix = "custom")
public class CustomConfig {
    private List<String> whiteUrl;

    public List<String> getWhiteUrl() {
        return whiteUrl;
    }

    public void setWhiteUrl(List<String> whiteUrl) {
        this.whiteUrl = whiteUrl;
    }
}

三、再需要引用的类中注入

@Component
public class SendAspect {
    @Resource
    private CustomConfig customConfig;
    ...
    customConfig.getWhiteUrl()
    ...
}

自定义实体类

一、aplication.yml

sw:
  pool-size: 10
  kind-of-algorithm: SM3
  hm-infos:
    - ip: 127.0.0.1
      port: 8008
      passwd: 123123
      connect-timeout: 300
      service-timeout: 300
      heartbeat: 60
      index: 1
      loginProtocol: 0x02000000

二、配置类和自定义实体

@Data
@Configuration
@ConfigurationProperties(prefix = "sw")
public class SwConfig {
    private List<CustomHM> hsInfos;
    private Integer poolSize;
    /**
     * Hash运算支持的算法:SM3WithoutID/SM3/SHA1/SHA256/SHA384/SHA512
     */
    private String kindOfAlgorithm;

    @Bean
    public MessageDigest messageDigest() throws NoSuchAlgorithmException {
        List<HSInfo> hsmInfoList = hsInfos.stream().map(h -> {
            HSInfo hsInfo = new HSInfo(h.getIp(), h.getPort(), h.getPasswd(), h.getConnectTimeout(), h.getServiceTimeout());
            hsInfo.setIndex(h.getIndex());
            hsInfo.setHeartbeat(h.getHeartbeat());
            hsInfo.setLoginProtocol(h.getLoginProtocol());
            return hsInfo;
        }).collect(Collectors.toList());
        SwxaProvider swxaProvider = new SwxaProvider(hsmInfoList, poolSize);
        if (Security.getProvider(SwxaProvider.PROVIDER_NAME) == null) {
            Security.addProvider(swxaProvider);
        }
        //定义摘要类对象
        return MessageDigest.getInstance(kindOfAlgorithm, swxaProvider);
    }

    @Getter
    @Setter
    @Configuration
    @ConfigurationProperties(prefix = "sw.hm-infos")
    public static class CustomHM {
        private Integer index;
        private String ip;
        private Integer port;
        private String passwd;
        private Integer connectTimeout;
        private Integer serviceTimeout;
        private Integer heartbeat;
        private Integer loginProtocol;
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值