美文网首页coder
使用@PropertySource同时加载properties和

使用@PropertySource同时加载properties和

作者: S拒绝拖延 | 来源:发表于2020-03-13 23:41 被阅读0次

    1.编写加载类MixPropertySourceFactory继承DefaultPropertySourceFactory

    package com.liberty.util;
    
    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.DefaultPropertySourceFactory;
    import org.springframework.core.io.support.EncodedResource;
    
    import java.io.IOException;
    import java.util.Properties;
    
    public class MixPropertySourceFactory 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();
        }
    }
    
    

    2.填写@PropertySource属性

    @PropertySource(value = "classpath:datasource.properties", factory = MixPropertySourceFactory.class)
    

    相关文章

      网友评论

        本文标题:使用@PropertySource同时加载properties和

        本文链接:https://www.haomeiwen.com/subject/yimushtx.html