zoukankan      html  css  js  c++  java
  • springboot自定义yaml配置文件

    Spring Boot的默认不支持yaml文件,需要自定义一个factory

    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 java.io.FileNotFoundException;
    import java.io.IOException;
    import java.util.Properties;
    
    /**
     * @version 0.1.0
     * @description: 解析自定义yml文件
     **/
    public class YamlPropertySourceFactory implements PropertySourceFactory {
        @Override
        public PropertySource<?> createPropertySource(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;
            }
        }
    }
    
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.PropertySource;


    @Configuration @PropertySource(value
    = "classpath:env/${spring.profiles.active}/constant.yml", encoding = "UTF-8", factory = YamlPropertySourceFactory.class) @ConfigurationProperties(prefix = "constant") public class Constant { public static String UPLOAD_PATH; public void setUPLOAD_PATH(String UPLOAD_PATH) { Constant.UPLOAD_PATH = UPLOAD_PATH; } }
     
  • 相关阅读:
    qq链接
    HTML5获取地理坐标
    AJAX的同步和异步的区别
    取消版本控制
    格式化打印数组函数
    图片返回刷新
    从哪些方面优化网站
    朋友圈的基本数据结构设计是怎样的?既能做到完美阅读权限设置,又能兼顾性能?
    表单提交数据安全性验证
    自然世界的划分
  • 原文地址:https://www.cnblogs.com/patrick-king/p/14145527.html
Copyright © 2011-2022 走看看