Spring源码——Resource

来源:互联网 发布:吉林大学软件学院 编辑:程序博客网 时间:2024/05/09 05:07

Resource

定义

资源文件来自于classPath或者本地文件。

  1. /**
  2. * Interface for a resource descriptor that abstracts from the actual
  3. * type of underlying resource, such as a file or class path resource.
  4. *
  5. * <p>An InputStream can be opened for every resource if it exists in
  6. * physical form, but a URL or File handle can just be returned for
  7. * certain resources. The actual behavior is implementation-specific.
  8. *
基本方法
基本方法的单元测试以及输出
  1. /**
  2. * org.springframework.core.io.Resource test
  3. * Created by jinglongjun on 2017/3/30.
  4. */
  5. public class TestResource {
  6. @Test
  7. public void testResource() throws IOException {
  8. Resource resource = new ClassPathResource("spring.xml");
  9. System.out.println(resource.exists());
  10. System.out.println(resource.getDescription());
  11. System.out.println(resource.getURL().getPath());
  12. }
  13. }
输出结果:
  1. true
  2. class path resource [spring.xml]
  3. /Users/jinglongjun/programe/workspace/spring/target/test-classes/spring.xml

Resouce继承关系

ClassPathResource
通过给定的ClassLoader或者ClassPath来加载资源。
  1. /**
  2. * Create a new {@code ClassPathResource} for {@code ClassLoader} usage.
  3. * A leading slash will be removed, as the ClassLoader resource access
  4. * methods will not accept it.
  5. * @param path the absolute path within the classpath
  6. * @param classLoader the class loader to load the resource with,
  7. * or {@code null} for the thread context class loader
  8. * @see ClassLoader#getResourceAsStream(String)
  9. */
  10. public ClassPathResource(String path, ClassLoader classLoader) {
  11. Assert.notNull(path, "Path must not be null");
  12. String pathToUse = StringUtils.cleanPath(path);
  13. if (pathToUse.startsWith("/")) {
  14. pathToUse = pathToUse.substring(1);
  15. }
  16. this.path = pathToUse;
  17. this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
  18. }


0 0
原创粉丝点击