springboot 读取resources下的 properties配置文件

巧了我就是萌 提交于 2019-12-18 11:18:27

主要用到了spring框架的ClassPathResource,可以直接获取resources目录下的文件,而不用费半天劲写绝对路径了。

import org.springframework.core.io.ClassPathResource;
import java.io.*;
import java.util.Properties;

public class PropertitesUtil {
    public static  Properties props;

    static {
        try {
            readPropertiesFile("/model.properties");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Properties readPropertiesFile(String filePath) throws FileNotFoundException, IOException {
        try {
            ClassPathResource classPathResource = new ClassPathResource(filePath);
            InputStream inputStream =classPathResource.getInputStream();
            props = new Properties();
            props.load(new InputStreamReader(inputStream, "UTF-8"));
            return props;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getServiceBeanName(String modelName){
        String modelId = props.getProperty(modelName);
        return props.getProperty(modelId);
    }

    public static Long getModelId(String modelName){

        return Long.parseLong(props.getProperty(modelName));
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!