Springboot中加载自定义的yml配置文件

有一些配置需要单独提出来时,如果是properties文件可以@PropertySource注解直接进行加载,但如果是yml文件就需要进行处理
1、创建你的配置文件,比如config.yml,写入配置项
2、创建配置类,并加载配置文件

@Component
@Data
@Configuration
@PropertySource(value = {"classpath:/config.yml"}, factory = CompositePropertySourceFactory.class)
public class MyConfig {

    @Value("${query.pageSize}")
    public int pageSize;

}

3、自定义CompositePropertySourceFactory来加载yml文件
这里有个属性叫factory,默认的factory是DefaultPropertySourceFactory,默认值加载properties文件
我们只需要继承这个类,对其扩展即可

public class CompositePropertySourceFactory extends DefaultPropertySourceFactory {

    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource)
            throws IOException {
        String sourceName = Optional.ofNullable(name).orElse(resource.getResource().getFilename());
        if (!resource.getResource().exists()) {
            // return an empty Properties
            return new PropertiesPropertySource(sourceName, new Properties());
        } else if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
            Properties propertiesFromYaml = loadYaml(resource);
            return new PropertiesPropertySource(sourceName, propertiesFromYaml);
        } else {
            return super.createPropertySource(name, resource);
        }
    }
    /**
     * load yaml file to properties
     *
     * @param resource
     * @return
     * @throws IOException
     */
    private Properties loadYaml(EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        factory.afterPropertiesSet();
        return factory.getObject();
    }
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容