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

posted @ 2019-12-20 15:26  远古大人  阅读(3363)  评论(0编辑  收藏  举报