ClassPathResource加载资源文件用法 - 获取配置文件路径

ClassPathResource解析

先看Demo:

@Test
public void test() throws IOException {
    Resource res = new ClassPathResource("applicationContext.xml");
    InputStream input = res.getInputStream();
    Assert.assertNotNull(input);
}

内部源码:

public ClassPathResource(String path) {
    this(path, (ClassLoader) null);
}


public ClassPathResource(String path, ClassLoader classLoader) {
    Assert.notNull(path, "Path must not be null");
    String pathToUse = StringUtils.cleanPath(path);
    if (pathToUse.startsWith("/")) {
        pathToUse = pathToUse.substring(1);
    }
    this.path = pathToUse;
    this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
}


public ClassPathResource(String path, Class<?> clazz) {
    Assert.notNull(path, "Path must not be null");
    this.path = StringUtils.cleanPath(path);
    this.clazz = clazz;
}

获取资源内容:

@Override
public InputStream getInputStream() throws IOException {
    InputStream is;
    if (this.clazz != null) {
        is = this.clazz.getResourceAsStream(this.path);
    }
    else if (this.classLoader != null) {
        is = this.classLoader.getResourceAsStream(this.path);
    }
    else {
        is = ClassLoader.getSystemResourceAsStream(this.path);
    }
    if (is == null) {
        throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist");
    }
    return is;
}

所以类获取资源的方式有两种

Class获取和ClassLoader获取。

两种方法的Demo和区别:

Demo:
@Test
public void test1() {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

    // ClassLoader.getResource("")获取的是classpath的根路径
    System.out.println("a--- " + classLoader.getResource("").getPath());

    // new ClassPathResource()获取的是空路径
    System.out.println("b--- " + new ClassPathResource("/").getPath());
    System.out.println("b-1--- " + new ClassPathResource("").getPath());

    // Class.getResource("")获取的是相对于当前类的相对路径
    System.out.println("c--- " + this.getClass().getResource("").getPath());

    // Class.getResource("/")获取的是classpath的根路径
    System.out.println("d--- " + this.getClass().getResource("/").getPath());
}

输出:

a--- /E:/xie-my-install/devolop/eideaworkspace/ideatest/target/classes/
b--- 
b-1--- 
c--- /E:/xie-my-install/devolop/eideaworkspace/ideatest/target/classes/com/xie/util/
d--- /E:/xie-my-install/devolop/eideaworkspace/ideatest/target/classes/
区别
  • Class.getResource("")获取的是相对于当前类的相对路径
  • Class.getResource("/")获取的是classpath的根路径
  • ClassLoader.getResource("")获取的是classpath的根路径
  • new ClassPathResource("")。空路径,如果没有指定相对的类名,该类将从类的根路径开始寻找某个resource,如果指定了相对的类名,则根据指定类的相对路径来查找某个resource。
    (如果打成可执行jar包的话,可以使用这种写法在jar的同级目录下创建文件路径:new ClassPathResource("").getPath() + "/" + UUidUtil.getStrUUID() + ".jpg";)这个可能还没研究透彻
  • 在创建ClassPathResource对象时,我们可以指定是按Class的相对路径获取文件还是按ClassLoader来获取。
posted @ 2022-04-02 16:34  xiexie0812  阅读(4320)  评论(0编辑  收藏  举报