从.yml配置文件中读取属性值

从.yml配置文件中读取属性值


参考文章

springboot使用@PropertySource的默认factory是读取.properties文件属性。
如果要读取yml或者yaml格式的文件属性值,需要自定义一个YamlPropertySourceFactory

实现YamlPropertySourceFactory类
package com.example.demo.config;

import lombok.AllArgsConstructor;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.env.YamlPropertySourceLoader;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.DefaultPropertySourceFactory;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;


public class YamlPropertySourceFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource)
            throws IOException {

        // 指定配置路径中的文件名
        String filename = resource.getResource().getFilename() == null ? "" : resource.getResource().getFilename();

        // 资源为空,则会抛出异常
        resource.getInputStream();

        // 配置文件为 properties 文件,调用原逻辑
        if (resource == null || filename.endsWith(".properties")) {
            return super.createPropertySource(name, resource);
        }
        // yml文件 或 yaml文件,则使用yaml属性源加载器加载并返回标准属性源
        else if (filename.endsWith(".yml") || filename.endsWith(".yaml")) {
            return new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource()).get(0);
        }
        // 非以上情况,则直接抛出异常,提示格式错误
        else {
            throw new IOException("file format error! only support: properties, yml, yaml!");
        }
    }
}
关联的对象类

通过@PropertySource来指定配置文件路径

package com.example.demo.config;

import lombok.Data;
import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

import java.io.Serializable;

@ConfigurationProperties(prefix = "test")
@Component
@PropertySource(value="classpath:test.yml",factory = YamlPropertySourceFactory.class, encoding = "utf-8")
@Data
public class TestConfig implements Serializable{
    private String userName;
    private String password;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值