zoukankan      html  css  js  c++  java
  • 关于@PropertySource注解对于yml的支持

    @PropertySource只对properties文件可以进行加载,但对于yml或者yaml不能支持。
    追寻源码。

    public class DefaultPropertySourceFactory implements PropertySourceFactory {
        public DefaultPropertySourceFactory() {
        }
    
        public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
            return name != null ? new ResourcePropertySource(name, resource) : new ResourcePropertySource(resource);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    我们只需要继承DefaultPropertySourceFactory类并修改就可以了。

    public class YamlConfigFactory extends DefaultPropertySourceFactory {
    
        @Override
        public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
            String sourceName = name != null ? name : resource.getResource().getFilename();
            if (!resource.getResource().exists()) {
                return new PropertiesPropertySource(sourceName, new Properties());
            } else if (sourceName.endsWith(".yml") || sourceName.endsWith(".yaml")) {
                Properties propertiesFromYaml = loadYml(resource);
                return new PropertiesPropertySource(sourceName, propertiesFromYaml);
            } else {
                return super.createPropertySource(name, resource);
            }
        }
    
        private Properties loadYml(EncodedResource resource) throws IOException {
            YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
            factory.setResources(resource.getResource());
            factory.afterPropertiesSet();
            return factory.getObject();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    
    @PropertySource(value = {"classpath:dog.yml"},factory = YamlConfigFactory.class)
    @Component
    @ConfigurationProperties(prefix = "dog")
    public class Dog {
    
        private String name ;
        private String age ;
    
  • 相关阅读:
    ipad 横屏 竖屏 CSS
    播放多个音视频文件
    插入百度地图
    js getByClass函数封装
    jq 测试是否到页面最底端
    python字符串跟整型互转
    day01-day04总结- Python 数据类型及其用法
    斐波那契数列的非递归
    LeetCode: 3SumClosest
    LeetCode: 3Sum
  • 原文地址:https://www.cnblogs.com/suizhikuo/p/13273257.html
Copyright © 2011-2022 走看看