Spring ClassPathResource加載資源文件詳解


先看Demo

@Test
public void testClassPathResource() throws IOException {
    Resource res = new ClassPathResource("resource/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;
}

獲取資源內容

/**
 * This implementation opens an InputStream for the given class path resource.
 * @see java.lang.ClassLoader#getResourceAsStream(String)
 * @see java.lang.Class#getResourceAsStream(String)
 */
@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獲取。

@Test
public void testResouce() {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    System.out.println(loader.getResource("").getPath());
    System.out.println(this.getClass().getResource("").getPath());
    System.out.println(this.getClass().getResource("/").getPath());
    System.out.println(System.getProperty("user.dir"));
}

運行結果:

/home/temp/spring_test/target/test-classes/
/home/temp/spring_test/target/test-classes/com/test/spring/spring_test/
/home/temp/spring_test/target/test-classes/
/home/temp/spring_test
//獲取的是相對於當前類的相對路徑
Class.getResource("")
//獲取的是classpath的根路徑
Class.getResource("/")
//獲取的是classpath的根路徑
ClassLoader.getResource("")

總結

在創建ClassPathResource對象時,我們可以指定是按Class的相對路徑獲取文件還是按ClassLoader來獲取。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM