getClassLoader()获取.properties路径问题

it2024-06-24  40

不多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的,所以写 / 则会从根目录下查找资源。

最新回复(0)