SpringBoot将yml文件写入内存

245 阅读1分钟

test.yml

# 注释
key1: value1
key2: value2
key3: value3

PropertiesUtils

import cn.hutool.core.io.FileUtil;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

public class PropertiesUtils {

    private static final Logger logger = LoggerFactory.getLogger(PropertiesUtils.class);
    public Properties properties;

    // 传入配置文件名称,可以多个
    public PropertiesUtils(String... resourcesPaths) {
        load(resourcesPaths);
    }

    // 加载配置文件信息
    private void load(String[] resourcesPaths) {
        properties = new Properties();
        for (String location : resourcesPaths) {
//            InputStream is = null;
            InputStreamReader is = null;
            try {
//                这种会乱码
//                is = new FileInputStream(getAbsolutePath(location));
                is = new InputStreamReader(getClass().getResourceAsStream("/" + location), StandardCharsets.UTF_8);
                properties.load(is);
            } catch (Exception ex) {
                logger.error("Could not load properties from path:" + location + ", " + ex.getMessage());
            } finally {
                IOUtils.closeQuietly(is);
            }
        }
    }

    // 获取根据key获取value
    public Object getValue(String key) {
        if (properties.containsKey(key)) {
            return properties.getProperty(key);
        }
        return "";
    }

    // 获取文件绝对路径
    public String getAbsolutePath(String filename) throws URISyntaxException {
        if (!FileUtil.isAbsolutePath(filename)) {
            filename = PropertiesUtils.class.getClassLoader().getResource(filename).toURI().getPath();
        }
        return filename;
    }
}

TestUtil

import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

@Component
public class TestUtil {

    public static Map<String, String> testMap = new HashMap<>();

    @PostConstruct
    public void init(){
        long startTime = System.currentTimeMillis();
        PropertiesUtils properties = new PropertiesUtils("test.yml");
        // 遍历获取key value
        for (Map.Entry<Object, Object> entry : properties.properties.entrySet()) {
            Object key = entry.getKey();
            Object value = entry.getValue();

            testMap.put(key.toString(), value.toString());
        }
        System.out.println("load time :" + (System.currentTimeMillis() - startTime) + "ms");
    }
}