配置类通过PropertySource注解加载自定义yml配置文件

本文介绍如何使用Spring Boot自定义YAML属性源工厂,实现从YAML文件加载配置,并通过配置类注入属性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  首先定义一个YamlPropertySourceFactory,参考https://mdeinum.github.io/2018-07-04-PropertySource-with-yaml-files/

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

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

public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(@Nullable String name, EncodedResource resource) throws IOException {
        Properties propertiesFromYaml = loadYamlIntoProperties(resource);
        String sourceName = name != null ? name : resource.getResource().getFilename();
        return new PropertiesPropertySource(sourceName, propertiesFromYaml);
    }

    private Properties loadYamlIntoProperties(EncodedResource resource) throws FileNotFoundException {
        try {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        } catch (IllegalStateException e) {
            // for ignoreResourceNotFound
            Throwable cause = e.getCause();
            if (cause instanceof FileNotFoundException)
                throw (FileNotFoundException) e.getCause();
            throw e;
        }
    }
}
然后定义配置类,如下(PropertySource默认支持properties文件,若加载properties文件则不需要定义YamlPropertySourceFactory)
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;


@Configuration
@PropertySource(factory = YamlPropertySourceFactory.class, value = "classpath:config/xxx.yml")
@Data
public class XxxConfig {
    /**
     * xxx.yml放在resources/config目录下
     * fieldName是yml文件中的key值   
     */
    @Value("${fieldName}")
    private String fieldName;
   
}

yml文件中key值的冒号后面要留一个空格,包含特殊字符的value值要用单引号括起来。例

fieldName: '[xxx]'

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值