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

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

作者: 江南Ryan | 来源:发表于2018-12-20 18:16 被阅读0次

    在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
    

    相关文章

      网友评论

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

          本文链接:https://www.haomeiwen.com/subject/nclukqtx.html