java自定义类加载properties文件

properties文件放在resourses文件下

name=123
age=1
address=南京
phone=123456
url=http://www.baidu.com
static Properties prop = null ;
public static void loadProperty(){
//3种方法加载resourses目录下的spring.properties文件
       // InputStream is = this.getClass().getClassLoader().getResourceAsStream("spring.properties");
       InputStream is1 = PropertiesUtil.class.getResourceAsStream("/spring.properties");
       // InputStream is1 = PropertiesUtil.class.getClassLoader().getResourceAsStream("spring.properties");
        try {
            prop = new Properties();
            prop.load(is1);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (is1 != null) {
                try {
                    is1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

//返回配置文件中的key对应的值
public  static  String getProperty(String key){
      if(prop == null){
            loadProperty();
      }
      return prop.getProperty(key);
    }

//返回配置文件中的key对应的值,为null则给一个自定义的默认值
public  static  String getProperty2(String key,String defaultValue){
        if(prop == null){
            loadProperty();
        }
        return (String) prop.getProperty(key,defaultValue);
    }

this代表当前对象,不能在static方法中使用

重点:
3种方法加载resourses目录下的spring.properties文件,如:PropertiesUtil.class.getClassLoader().getResourceAsStream(“spring.properties”);
加载的是target下的属性文件
而项目 <packaging>pom</packaging>打包的target中没有resourses下的属性文件,这样就会加载不到属性文件
解决办法:1.将pom改为jar/war 打包后在换回来
2.手动加入属性文件(xml文件不能手动加入)

后续更新不需要重启服务器的情况下动态加载配置文件中的内容。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值