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来获取。