springboot利用YamlPropertiesFactoryBean读取自定义yaml配置文件

  1. 首先确保依赖已被添加:
// https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-configuration-processor
implementation 'org.springframework.boot:spring-boot-configuration-processor:2.2.6.RELEASE'
  1. 定义自定义配置文件:
myyaml:
  str: 字符串可以不加引号
  specialStr: "双引号输出\n特殊字符"
  specialStr2: '单引号可转义\n特殊字符'
  flag: false
  num: 123
  Dnum: 3.14159
  list:
    - one
    - two
    - two
  set: [1,2,2,3]
  map: {k1: v1, k2: v2}
  positions:
    - name: zhangsan
      salary: 15000.00
    - name: lisi
      salary: 18888.88
  1. 编写对应该配置文件的配置类:
@Configuration
@ConfigurationProperties(prefix = "myyaml")
@Data
public class ConfigYML {

    private String str;
    private String specialStr;
    private String specialStr2;
    private Boolean flag;
    private Integer num;
    private Double dNum;

    private List<Object> list;
    private Set<Object> set;

    private Map<String, Object> map;
    private List<Person> positions;
}
  1. 加载并装配YML格式自定义配置文件(本测试文件存储在config目录下的myconfig目录下),该方法可放在启动类中:
    @Bean
    public static PropertySourcesPlaceholderConfigurer properties() throws FileNotFoundException{

        try {
            PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
            YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
            //自定义yaml文件的存储路径
            yaml.setResources(new ClassPathResource("/myconfig/ymltest.yml"));
            configurer.setProperties(Objects.requireNonNull(yaml.getObject()));
            return configurer;
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException){
                throw (FileNotFoundException) e.getCause();
            }
            throw e;
        }
    }
  1. 测试可用
    在这里插入图片描述
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值