首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >2018-04-27 读配置文件到静态变量中,加载properties到static变量field

2018-04-27 读配置文件到静态变量中,加载properties到static变量field

作者头像
Albert陈凯
发布2018-05-04 11:57:26
1.3K0
发布2018-05-04 11:57:26
举报
文章被收录于专栏:Albert陈凯Albert陈凯

项目的配置文件要写到jar档外面,提供给运维人员更改,基于这个需求,就会有很多的常量需要从外部文件读取进来

JAVA最常见的就是properties文件,提供key,value的方式,

本来想用Spring的@Value,但发现注入不进来

可能是我搜索的关键词不对,搜了半天竟然没有解决方法

尝试搜索的关键字

  • 读配置文件到静态变量中
  • 静态变量读取 properties 文件
  • Read property value from properties file in static field of class using Java based spring configuration.

网络上面提供的方法还蛮多的

  Object.class.getClassLoader().getResourceAsStream("config.properties");

读classpath中的配置档可以,但读本地文件系统就没有办法 file:/var/xxxx这样读不到

最终可以用的方法也比较简单

@Data
@Log4j2
public class Constants {


    public static Properties PROPERTIES;

    static {

        String pathString = "/var/config.properties";
        File file = new File(pathString);
        PROPERTIES = new Properties();
        try {
            FileInputStream fis = new FileInputStream(file);
            PROPERTIES.load(fis);
            log.debug("PROPERTIES : " + PROPERTIES);
            PARAM2= PROPERTIES.getProperty("albert.chen.param2").trim();
          
        } catch (IOException e) {
            log.error("Read Configuration File error" + e);
        }
    }

    private VendorPropertiesConstants() {
    }

    public static String PARAM1= PROPERTIES.getProperty("albert.chen.param1").trim().toUpperCase();
    public static String PARAM2;


}

config.properties

albert.chen.param1=123
albert.chen.param2=test

Application.java

import lombok.extern.log4j.Log4j2;

/**
 * @author albert on 4/26/2018
 */
@Log4j2
public class Application {

    public static void main(String[] args) {


        System.out.println(Constants .PARAM1);
        System.out.println(Constants .PARAM2);


    }

}

参考文档: https://blog.csdn.net/chengly0129/article/details/49493297 https://www.againfly.com/flytag_292.html https://www.jianshu.com/p/127310cb90e0 http://www.mkyong.com/java/java-getresourceasstream-in-static-method/

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018.04.27 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • config.properties
  • Application.java
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档