getClassLoader()获取.properties路径问题

不多bb,直接上图
代码片段如下:

private static Properties pro = new Properties();

static {
  //InputStream is = BeanFactory.class.getClassLoader().getResourceAsStream("ApplicationContext.properties");
   InputStream is = BeanFactory.class.getResourceAsStream("/ApplicationContext.properties");
   
   try {
       pro.load(is);
   } catch (IOException e) {
       e.printStackTrace();
   }
}

idea的文件存放如下:
在这里插入图片描述

文章解释:

第一种使用类的加载器:
BeanFactory.class.getClassLoader().getResourceAsStream(“ApplicationContext.properties”);

使用类加载器时,name要用相对路径的写法,其相对值是相对于ClassLoader的,因为ClassLoader是一棵树,所以这个相对路径和ClassLoader树上的任何一个ClassLoader相对比较后可以找到文件

第二种不使用类的加载器:
BeanFactory.class.getResourceAsStream("/ApplicationContext.properties");

绝对路径的写法是以 / 为开头的,
getResourceAsStream会在BeanFactory对应lyy.utity包下查找相应的资源,因为utity包下是没有properties的,所以写 / 则会从根目录下查找资源。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值