SpringBoot 使用 @PropertySource 加载自定义 yml 文件

LIXI.FUN - SpringBoot 使用 @PropertySource 加载自定义 yml 文件

@PropertySource 本身 支持 .properties 格式的文件,后缀可以不为 .properties,但是内容格式得按照 .properties 的格式来。

例如:

my.properties

myp.name=lixi
myp.age=8
/**
* 当直接指定 .properties 文件的时候,可以正常拿到值
*/
@PropertySource(value = "classpath:my.properties")

/**
* 当直接指定 .yml 文件的时候
* 并不能拿到文件中的属性的值,所有的引用类型为 `null`,基本类型为其默认值
*/
@PropertySource(value = "classpath:my.yml")

如果想要 @PropertySource 读取 .yml 格式的文件需要自定义 YamlPropertySourceFactory

myy:
    name: lixifun
    age: 88

使用方式

import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Data
@Configuration
@ConfigurationProperties(prefix = "myy")
@PropertySource(value = "classpath:my.yml", factory = YamlPropertySourceFactory.class)
public class MyYamlConfig {

    private String name;
    private Integer age;

}

YamlPropertySourceFactory.java 的代码内容:

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.util.Properties;

public class YamlPropertySourceFactory implements PropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource encodedResource) {

        Resource resource = encodedResource.getResource();

        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource);

        Properties props = factory.getObject();

        return new PropertiesPropertySource(resource.getFilename(), props);
    }
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

lixifun

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值