静态类在加载之初获取文档中的配置文件

2018-12-20  本文已影响0人  江南Ryan

在Spring中静态类加载的时候无法加载xml文件,但是可以加载property文件,事例如下:
在resource目录中建立一个*.properties文件,如下:
本例中建立config.properties


image.png
protocolMode=pegasus

读取的工具类代码如下:

public class UtilProperty {

    private static final Logger logger=LogManager.getLogger(UtilProperty.class);

    private static Properties p=null;

    static {
         p = new Properties();

        InputStream stream = UtilProperty.class.getClassLoader().getResourceAsStream("config.properties");
        try {
            p.load(stream);
        } catch (IOException e) {
            logger.info("读取文件异常");
            e.printStackTrace();
        }

    }

    public String getValueMethod(){
        return p.getProperty("protocolMode")==null?null:p.getProperty("protocolMode").toString();
    }

}

使用代码:

public class Test01 {

    public static void main(String[] args){

        UtilProperty util = new UtilProperty();
        String value = util.getValueMethod();
        System.out.println("the value : "+value);

    }
}

结果输出如下:

the value : pegasus
上一篇下一篇

猜你喜欢

热点阅读