17.Spring Boot加载指定YML文件

目录


Spring Boot专栏目录(点击进入…)



SpringBoot加载指定YML文件

Spring Boot默认支持properties和yml配置文件的读取,前者格式简单,但是只支持键值对。如果需要表达列表,最好使用YAML格式。

Spring Boot支持自动加载约定名称的配置文件,仅支持指定路径下指定名称的配置文件;例如application.yml。当自定义指定路径加载配置文件时,properties文件使用@PropertySource注解即可,但该注解并不支持加载yaml

老版本的SpringBoot可以通过@ConfigurationProperties的方式指定location;1.0.4之后该属性就取消了

@ConfigurationProperties(locations={"classpath:myconfig.yml"})

(1)YamlPropertiesFactoryBean:将yaml文件加载为Properties

@Configuration
public class YamlPropertyConfig {

    /**
     * 将yaml文件转为properties并设置到属性源
     * @return
     */
    @Bean
    public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
        YamlPropertiesFactoryBean yamlProperties = new YamlPropertiesFactoryBean();
        yamlProperties.setResources(new ClassPathResource("generator.yml"));
        propertySourcesPlaceholderConfigurer.setProperties(yamlProperties.getObject());
        return propertySourcesPlaceholderConfigurer;
    }

}

(2)YamlPropertySourceLoader:将yaml文件加载为Map

@Configuration
public class YamlPropertyConfig {

    @Bean
    public PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer2() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
        MutablePropertySources sources = new MutablePropertySources();
        try {
            List<PropertySource<?>> generator = loader.load("generator", new ClassPathResource("generator.yml"));
            generator.stream().forEach(item -> {
                sources.addLast(item);
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
        configurer.setPropertySources(sources);
        return configurer;
    }
    
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

未禾

您的支持是我最宝贵的财富!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值