ResourceLoader

Spring的ApplicationContext继承了ResourceLoader接口.这个接口主要就是可以加载各种resource..

接口还是比较简单的:

 /*
* Copyright 2002-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/ package org.springframework.core.io; import org.springframework.util.ResourceUtils; /**
* Strategy interface for loading resources (e.. class path or file system
* resources). An {@link org.springframework.context.ApplicationContext}
* is required to provide this functionality, plus extended
* {@link org.springframework.core.io.support.ResourcePatternResolver} support.
*
* <p>{@link DefaultResourceLoader} is a standalone implementation that is
* usable outside an ApplicationContext, also used by {@link ResourceEditor}.
*
* <p>Bean properties of type Resource and Resource array can be populated
* from Strings when running in an ApplicationContext, using the particular
* context's resource loading strategy.
*
* @author Juergen Hoeller
* @since 10.03.2004
* @see Resource
* @see org.springframework.core.io.support.ResourcePatternResolver
* @see org.springframework.context.ApplicationContext
* @see org.springframework.context.ResourceLoaderAware
*/
public interface ResourceLoader { /** Pseudo URL prefix for loading from the class path: "classpath:" */
String CLASSPATH_URL_PREFIX = ResourceUtils.CLASSPATH_URL_PREFIX; /**
* Return a Resource handle for the specified resource.
* The handle should always be a reusable resource descriptor,
* allowing for multiple {@link Resource#getInputStream()} calls.
* <p><ul>
* <li>Must support fully qualified URLs, e.g. "file:C:/test.dat".
* <li>Must support classpath pseudo-URLs, e.g. "classpath:test.dat".
* <li>Should support relative file paths, e.g. "WEB-INF/test.dat".
* (This will be implementation-specific, typically provided by an
* ApplicationContext implementation.)
* </ul>
* <p>Note that a Resource handle does not imply an existing resource;
* you need to invoke {@link Resource#exists} to check for existence.
* @param location the resource location
* @return a corresponding Resource handle
* @see #CLASSPATH_URL_PREFIX
* @see org.springframework.core.io.Resource#exists
* @see org.springframework.core.io.Resource#getInputStream
*/
Resource getResource(String location); /**
* Expose the ClassLoader used by this ResourceLoader.
* <p>Clients which need to access the ClassLoader directly can do so
* in a uniform manner with the ResourceLoader, rather than relying
* on the thread context ClassLoader.
* @return the ClassLoader (only {@code null} if even the system
* ClassLoader isn't accessible)
* @see org.springframework.util.ClassUtils#getDefaultClassLoader()
*/
ClassLoader getClassLoader(); }

我感觉主要可能就是getResource方法了.

具体使用

实验如下:

 @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:test-application-context.xml")
public class ResourceLoaderTest implements ApplicationContextAware {
ApplicationContext applicationContext; @Test
public void testLoadResource() throws IOException { Resource resource = applicationContext.getResource("classpath:test.properties");
System.out.println(resource.exists()); // true Resource resource2 = applicationContext.getResource("/test.properties");
System.out.println(resource2.exists()); // true Resource resource3 = applicationContext.getResource("test.properties");
System.out.println(resource3.exists()); // true Resource resource4 = applicationContext.getResource("classpath:1.html");
System.out.println(FileUtils.readFileToString(resource4.getFile())); // 文件内容 Resource resource5 = applicationContext.getResource("https://www.baidu.com/");
System.out.println(IOUtils.toString(resource5.getInputStream())); // 网页内容 Resource resource6 = applicationContext.getResource("/spring/Config.class");
System.out.println(resource6.exists()); // true Resource resource7 = applicationContext.getResource("org/springframework/context/support/GenericApplicationContext.class");
System.out.println(resource7.exists()); // true
} @Test
public void a() {
System.out.println(1);
} @Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}

实验中发现:

1.可以通过classpath:XXX下载classpath下的资源

2.可以通过/XXX也是加载classpath下的资源

3.直接XXX,可以根据不同的协议去加载资源(比如http),没有的话去加载classpath下的资源

4.不光可以加载classes下的资源,也可以加载lib里jar里面的资源.

我用的junit 测试,applicationcontext是GenericApplicationContext的实例,getResource方法调的是DefaultResourceLoader的实现

     @Override
public Resource getResource(String location) {
Assert.notNull(location, "Location must not be null");
if (location.startsWith("/")) {
return getResourceByPath(location);
}
else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
}
else {
try {
// Try to parse the location as a URL...
URL url = new URL(location);
return new UrlResource(url);
}
catch (MalformedURLException ex) {
// No URL -> resolve as resource path.
return getResourceByPath(location);
}
}
}

从代码中我们可以发现,

1.如果是/开头的资源,会调用getResourceByPath方法,最后返回的其实也是ClassPathResource

     /**
* Return a Resource handle for the resource at the given path.
* <p>The default implementation supports class path locations. This should
* be appropriate for standalone implementations but can be overridden,
* e.g. for implementations targeted at a Servlet container.
* @param path the path to the resource
* @return the corresponding Resource handle
* @see ClassPathResource
* @see org.springframework.context.support.FileSystemXmlApplicationContext#getResourceByPath
* @see org.springframework.web.context.support.XmlWebApplicationContext#getResourceByPath
*/
protected Resource getResourceByPath(String path) {
return new ClassPathContextResource(path, getClassLoader());
} /**
* ClassPathResource that explicitly expresses a context-relative path
* through implementing the ContextResource interface.
*/
protected static class ClassPathContextResource extends ClassPathResource implements ContextResource { public ClassPathContextResource(String path, ClassLoader classLoader) {
super(path, classLoader);
} @Override
public String getPathWithinContext() {
return getPath();
} @Override
public Resource createRelative(String relativePath) {
String pathToUse = StringUtils.applyRelativePath(getPath(), relativePath);
return new ClassPathContextResource(pathToUse, getClassLoader());
}
}

2.如果是classpath:开头,也是ClassPathResource

3.如果是XXX.XX的话用URL去找资源失败的话,还是会返回ClassPathResource,成功的话就是返回UrlResource.

然后我想到了1个问题.就是我们在项目中加载文件的时候经常会用classpath*:.............这种形式在这里似乎没有出现,可能是Servlet环境下的ApplicationContext覆盖了getResource方法,也可能是其他方法加载资源..等我学习了其他的applicationcontext就明白了...可能会再做分享.

小结

我感觉使用resourceloader相比于getResource里面写classpath:xxxxxx比自己去getClass().getResource的好处在于:

1.更简单清晰...看过去就知道资源是相对于classpath的...

2.resourceloader产生的ClassPathResource对于你传入的路径字符串是会转化的...你传入的windows的\也会被转化成/..而getClass那种并不会....所以getClass().getResource在传入的String拼接的时候如果用到了File.sperator可能会找不到资源,而resourceloader不会...不过更多的时候可能都不需要拼接...直接写1个完整的字符串用/分割路径就行了...

Spring 学习记录4 ResourceLoader的更多相关文章

  1. Spring 学习记录8 初识XmlWebApplicationContext(2)

    主题 接上文Spring 学习记录7 初识XmlWebApplicationContext refresh方法 refresh方法是定义在父类AbstractApplicationContext中的. ...

  2. 我的Spring学习记录(二)

    本篇就简单的说一下Bean的装配和AOP 本篇的项目是在上一篇我的Spring学习记录(一) 中项目的基础上进行开发的 1. 使用setter方法和构造方法装配Bean 1.1 前期准备 使用sett ...

  3. 我的Spring学习记录(四)

    虽然Spring管理这我们的Bean很方便,但是,我们需要使用xml配置大量的Bean信息,告诉Spring我们要干嘛,这还是挺烦的,毕竟当我们的Bean随之增多的话,xml的各种配置会让人很头疼. ...

  4. 我的Spring学习记录(五)

    在我的Spring学习记录(四)中使用了注解的方式对前面三篇做了总结.而这次,使用了用户登录及注册来对于本人前面四篇做一个应用案例,希望通过这个来对于我们的Spring的使用有一定的了解. 1. 程序 ...

  5. Spring 学习记录3 ConversionService

    ConversionService与Environment的关系 通过之前的学习(Spring 学习记录2 Environment),我已经Environment主要是负责解析properties和p ...

  6. Spring 学习记录6 BeanFactory(2)

    主题 除了Spring 学习记录5 BeanFactory 里写的几个接口外,BeanFactory的实现类还实现了一些其他接口,这篇文章主要介绍这些接口和实现类. 结构 DefaultListabl ...

  7. Spring学习记录(九)---通过工厂方法配置bean

    1. 使用静态工厂方法创建Bean,用到一个工厂类 例子:一个Car类,有brand和price属性. package com.guigu.spring.factory; public class C ...

  8. Spring学习记录(七)---表达式语言-SpEL

    SpEL---Spring Expression Language:是一个支持运行时查询和操作对象图表达式语言.使用#{...}作为定界符,为bean属性动态赋值提供了便利. ①对于普通的赋值,用Sp ...

  9. Spring 学习记录5 BeanFactory

    主题 记录我对BeanFactor接口的简单的学习. BeanFactory我感觉就是管理bean用的容器,持有一堆的bean,你可以get各种bean.然后也提供一些bean相关的功能比如别名呀之类 ...

随机推荐

  1. Servlet实现数字字母验证码图片(二)

    Servlet实现数字字母验证码图片(二): 生成验证码图片主要用到了一个BufferedImage类,如下:

  2. selenium python实例脚本1

    #!/usr/local/bin/python3 # coding=utf-8 #统一编码from selenium import webdriverfrom time import sleep#im ...

  3. lua不支持的泛型方法

    1.没有泛型约束 2.缺少带约束的泛型参数 3.泛型约束必须为class /// <summary> /// 不支持生成lua的泛型方法(没有泛型约束) /// </summary& ...

  4. UVA12716 GCD XOR 数论数学构造

    版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/u010682557/article/details/36204645 题目给你一个N,让你求 两个数 ...

  5. Linux中源码安装编译Vim

    Linux中源码安装编译Vim Linux下学习工作少不了编辑器,Vim能使你的工作效率成倍的提高.在Ubuntu上安装vim使用命令直接安装很简单.但有时还是需要自己手动编译安装.例如: vim中的 ...

  6. 1.Python3关于文件的操作

    1.写了一个简单的Demo,就是向txt文本写入内容,最初代码如下: file = open("D:/Users/nancy/python.txt","wb") ...

  7. OpenCL入门

    初入OpenCL,做个记录. 在Windows下开发OpenCL程序,必须先下载OpenCL的SDK,现在AMD,NVIDIA,Intel均提供各自的OpenCL库,基本是大同小异.安装好SDK后新建 ...

  8. DS05--查找

    一.学习总结 1.查找的思维导图 2.查找学习体会 2.1 关联容器和顺序容器 c++中有两种类型的容器:顺序容器和关联容器,顺序容器主要有:vector.list.deque等.其中vector表示 ...

  9. 杂项-数学软件:Mathematica

    ylbtech-杂项-数学软件:Mathematica Mathematica是一款科学计算软件,很好地结合了数值和符号计算引擎.图形系统.编程语言.文本系统.和与其他应用程序的高级连接.很多功能在相 ...

  10. @BindingAnnotation

    (1) 如果 一个接口只有一个实现,使用这种连接注解就可以: bind(XXInterface.class).to(XXImpl.class); @Inject XXInterface xxInter ...