Spring 学习记录4 ResourceLoader
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的更多相关文章
- Spring 学习记录8 初识XmlWebApplicationContext(2)
主题 接上文Spring 学习记录7 初识XmlWebApplicationContext refresh方法 refresh方法是定义在父类AbstractApplicationContext中的. ...
- 我的Spring学习记录(二)
本篇就简单的说一下Bean的装配和AOP 本篇的项目是在上一篇我的Spring学习记录(一) 中项目的基础上进行开发的 1. 使用setter方法和构造方法装配Bean 1.1 前期准备 使用sett ...
- 我的Spring学习记录(四)
虽然Spring管理这我们的Bean很方便,但是,我们需要使用xml配置大量的Bean信息,告诉Spring我们要干嘛,这还是挺烦的,毕竟当我们的Bean随之增多的话,xml的各种配置会让人很头疼. ...
- 我的Spring学习记录(五)
在我的Spring学习记录(四)中使用了注解的方式对前面三篇做了总结.而这次,使用了用户登录及注册来对于本人前面四篇做一个应用案例,希望通过这个来对于我们的Spring的使用有一定的了解. 1. 程序 ...
- Spring 学习记录3 ConversionService
ConversionService与Environment的关系 通过之前的学习(Spring 学习记录2 Environment),我已经Environment主要是负责解析properties和p ...
- Spring 学习记录6 BeanFactory(2)
主题 除了Spring 学习记录5 BeanFactory 里写的几个接口外,BeanFactory的实现类还实现了一些其他接口,这篇文章主要介绍这些接口和实现类. 结构 DefaultListabl ...
- Spring学习记录(九)---通过工厂方法配置bean
1. 使用静态工厂方法创建Bean,用到一个工厂类 例子:一个Car类,有brand和price属性. package com.guigu.spring.factory; public class C ...
- Spring学习记录(七)---表达式语言-SpEL
SpEL---Spring Expression Language:是一个支持运行时查询和操作对象图表达式语言.使用#{...}作为定界符,为bean属性动态赋值提供了便利. ①对于普通的赋值,用Sp ...
- Spring 学习记录5 BeanFactory
主题 记录我对BeanFactor接口的简单的学习. BeanFactory我感觉就是管理bean用的容器,持有一堆的bean,你可以get各种bean.然后也提供一些bean相关的功能比如别名呀之类 ...
随机推荐
- BZOJ2555 SubString【后缀自动机+LCT】
Description 懒得写背景了,给你一个字符串init,要求你支持两个操作 (1):在当前字符串的后面插入一个字符串 (2):询问字符串s在当前字符串中出现了几次?(作为连续子串) 你必须在线支 ...
- MAC OS环境下搭建基于Python语言的Selenium2自动化测试环境
#1安装Python Mac OS上自带python2.7,在此介绍安装python3.x版本 去官网下载Python for MAC版本 https://www.python.org 安装文件为pk ...
- Python 运行其他程序
10.4 运行其他程序 在Python中可以方便地使用os模块运行其他的脚本或者程序,这样就可以在脚本中直接使用其他脚本,或者程序提供的功能,而不必再次编写实现该功能的代码.为了更好地控制运行的进程, ...
- notepad++运行paython程序
cmd /k C:\Python30\python.exe "$(FULL_CURRENT_PATH)" & PAUSE & EXIT 添加引用的环境变量
- caddy server 默认https && http2的验证
1. 下载 https://caddyserver.com/ 注意选择应该包含的模块,此次包含了git 插件 2. 配置 使用 Caddyfile 内容如下: ro ...
- 14.Python使用Pillow教程
1.打算开始学习PIL,在命令行输入:pip3 install PIL,报错信息如下所示,后百度了下,发现:PIL仅支持到Python2.7,后来一群志愿者在此基础上创建了兼容性版本,为Pillow, ...
- 项目代码部署百度云(使用git部署,node环境)
学习做了一个小demo,总是在自己的电脑,和局域网上运行很没意思,现在就做点有意思的事情,将代码部署百度云. 1)首先你得进入百度云(直接百度,先要注册一个账号) 2)点击那个“应用引擎”,就会进入 ...
- string源码实现分析
最近写hashtable的实现的时候用模板类的思想,在普通int,long,double类型的时候测试时没问题的,当用到string的时候,一直有问题. 实现的equal函数是比较粗暴的使用两者所有对 ...
- 搭建基于hyperledger fabric的联盟社区(九) --检索状态数据库
一.启动elasticsearch服务 官网下载压缩包解压,进入bin目录启动: ./elasticsearch 通过ip访问 localhost:9200,可以看到如下信息 { name: &quo ...
- Unit06: 外部对象概述 、 window 对象 、 document 对象
Unit06: 外部对象概述 . window 对象 . document 对象 小代码演示: <!DOCTYPE html> <html> <head> < ...