Spring之ClassPathResource加載資源文件


先看Demo:

1 @Test
2 public void testClassPathResource() throws IOException {
3     Resource res = new ClassPathResource("resource/ApplicationContext.xml");
4     InputStream input = res.getInputStream();
5     Assert.assertNotNull(input);
6 }

 

再看內部源碼:

1 public ClassPathResource(String path) {
2     this(path, (ClassLoader) null);
3 }
1 public ClassPathResource(String path, ClassLoader classLoader) {
2     Assert.notNull(path, "Path must not be null");
3     String pathToUse = StringUtils.cleanPath(path);
4     if (pathToUse.startsWith("/")) {
5         pathToUse = pathToUse.substring(1);
6     }
7     this.path = pathToUse;
8     this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
9 }
1 public ClassPathResource(String path, Class<?> clazz) {
2     Assert.notNull(path, "Path must not be null");
3     this.path = StringUtils.cleanPath(path);
4     this.clazz = clazz;
5 }

 

獲取資源內容: 

 1 /**
 2  * This implementation opens an InputStream for the given class path resource.
 3  * @see java.lang.ClassLoader#getResourceAsStream(String)
 4  * @see java.lang.Class#getResourceAsStream(String)
 5  */
 6 @Override
 7 public InputStream getInputStream() throws IOException {
 8     InputStream is;
 9     if (this.clazz != null) {
10         is = this.clazz.getResourceAsStream(this.path);
11     }
12     else if (this.classLoader != null) {
13         is = this.classLoader.getResourceAsStream(this.path);
14     }
15     else {
16         is = ClassLoader.getSystemResourceAsStream(this.path);
17     }
18     if (is == null) {
19         throw new FileNotFoundException(getDescription() + " cannot be opened because it does not exist");
20     }
21     return is;
22 }

 源碼解讀:

該類獲取資源的方式有兩種:Class獲取ClassLoader獲取

兩種方法的區別:

再看Demo:

 1 @Test
 2 public void testResouce() {
 3     ClassLoader loader = Thread.currentThread().getContextClassLoader();
 4     System.out.println(loader.getResource("").getPath());
 5     
 6     System.out.println(this.getClass().getResource("").getPath());
 7     System.out.println(this.getClass().getResource("/").getPath());
 8 
 9     System.out.println(System.getProperty("user.dir"));
10 }

 

運行結果:

/home/sunny/workspace/spring-01/target/test-classes/
/home/sunny/workspace/spring-01/target/test-classes/com/me/spring/spring_01/
/home/sunny/workspace/spring-01/target/test-classes/
/home/sunny/workspace/spring-01

Class.getResource("")獲取的是相對於當前類的相對路徑

Class.getResource("/")獲取的是classpath的根路徑

ClassLoader.getResource("")獲取的是classpath的根路徑 

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


免責聲明!

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



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