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相关的功能比如别名呀之类 ...
随机推荐
- 如何组织一个同时面向 UWP/WPF/.Net Core 控制台的 C# 项目解决方案
希望写一个小型工具,给自己和需要的人.考虑到代码尽可能的复用,我准备采用 .Net Standard 来编写大多数核心代码,并基于 .Net Core 编写跨平台控制台入口,用 WPF 编写桌面端 U ...
- Unrecoverable error: corrupted cluster config file.
from: https://www.cnblogs.com/topicjie/p/7603227.html 缘起 正在欢乐的逗着孩子玩耍,突然间来了一通电话,值班人员告诉我误重启了一台服务器,是我负责 ...
- GitHub项目为己所用
1.下载 2.cmd 进入文件夹 3.mvn clean package 4.mvn install
- 《DSP using MATLAB》示例Example 8.27
%% ------------------------------------------------------------------------ %% Output Info about thi ...
- 控制已经打开的Excel
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...
- 再谈zabbix 邮件通知配置(不用脚本,简单配置就可以了)
备注: 安装过zabbix 的人,大家都应该了解,后者查询网上的资料邮件通知一般是编写一个脚本,即报警媒介类型,创建一个script类似的 然后编写脚本,进行发送,但是实际上,系统内置的邮件发送还是比 ...
- idea创建文件类型失败(xml之类的失效
https://blog.csdn.net/sutongxuevip/article/details/72832754
- 【转载】Leaflet 中文api
L.Map API各种类中的核心部分,用来在页面中创建地图并操纵地图. 使用 example // initialize the map on the "map" div with ...
- erlang的一些小技巧(不定期更新)
在任意节点热更新代码 rpc:call(Node,c,l,[Mod]) c和l的指的是code,library Erlang Shell隐藏的小技巧 f(). %%把所有绑定变量释放掉 f(Val). ...
- Spring boot Freemarker 获取ContextPath的方法
Spring boot Freemarker 获取ContextPath的两种方法: 1.自定义viewResolver,Spring boot中有一个viewResolver,这个和配置文件中的师徒 ...