zoukankan      html  css  js  c++  java
  • springboot读取 yaml或者properties文件几种方式

    方法一.可以专门写一个工具类读取所有非application的文件(单列模式)(用一个Map来保存所有配置文件)

          类工具代码如下:

    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Properties;
    
    public class ConfigPropertyUtil {
    
        private static final Logger logger = LoggerFactory.getLogger(ConfigPropertyUtil.class);
        private static Map<String,ConfigPropertyUtil> configPropertyMap = new HashMap<String,ConfigPropertyUtil>();
        private Properties properties = null;
    
        public static ConfigPropertyUtil getInstance(String propertyFileName){
            if(!configPropertyMap.containsKey(propertyFileName)){
                synchronized (ConfigPropertyUtil.class){
                    if(!configPropertyMap.containsKey(propertyFileName)){
                        ConfigPropertyUtil configPropertyUtil = new ConfigPropertyUtil(propertyFileName);
                        configPropertyMap.put(propertyFileName, configPropertyUtil);
                    }
                }
            }
            return configPropertyMap.get(propertyFileName);
        }
    
        private ConfigPropertyUtil(String propertyFileName){
            init(propertyFileName);
        }
    
        private void init(String propertyFileName){
            properties = new Properties();
            InputStream inputStream = ConfigPropertyUtil.class.getClassLoader().getResourceAsStream(propertyFileName);
            if(inputStream != null) {
                try {
                    properties.load(new InputStreamReader(inputStream,ConstantUtil.CHARSET_VALUE));
                } catch (IOException e) {
                    logger.error(String.format("config.properties file not found"));
                    e.printStackTrace();
                }
            }
        }
    
        public String getPropertyVal(String key){
            return this.properties.getProperty(key);
        }
    
        public Integer getIntPropertyVal(String key){
            return Integer.parseInt(this.getPropertyVal(key));
        }
    
    }

    方法二、@Value注解读取方式

    方法三、Environment读取方式(所有加载出来的配置都可以通过Environment注入获取到。只在加载进入java的classpath路径下)

    方法四、@PropertySource+@ConfigurationProperties注解读取方式

    方法五、@PropertySource+@Value注解读取方式

    参考:https://www.jianshu.com/p/982e36f42c67

  • 相关阅读:
    企业级 SpringBoot 教程 (九)springboot整合Redis
    03 网格系统
    02 表单
    01 排版
    客户端调用webSerices
    sql 一行转多行
    sql 多行转一行
    时间差计算 Stopwatch
    sql 游标
    Linq连接查询
  • 原文地址:https://www.cnblogs.com/yangcao/p/12073322.html
Copyright © 2011-2022 走看看