4.4.1  使用路径通配符加载Resource

前面介绍的资源路径都是非常简单的一个路径匹配一个资源,Spring还提供了一种更强大的Ant模式通配符匹配,从能一个路径匹配一批资源。

Ant路径通配符支持“?”、“*”、“**”,注意通配符匹配不包括目录分隔符“/”:

“?”:匹配一个字符,如“config?.xml”将匹配“config1.xml”;

“*”:匹配零个或多个字符串,如“cn/*/config.xml”将匹配“cn/javass/config.xml”,但不匹配匹配“cn/config.xml”;而“cn/config-*.xml”将匹配“cn/config-dao.xml”;

“**”:匹配路径中的零个或多个目录,如“cn/**/config.xml”将匹配“cn /config.xml”,也匹配“cn/javass/spring/config.xml”;而“cn/javass/config-**.xml”将匹配“cn/javass/config-dao.xml”,即把“**”当做两个“*”处理。

Spring提供AntPathMatcher来进行Ant风格的路径匹配。具体测试请参考cn.javass.spring.chapter4. AntPathMatcherTest。

public class AntPathMatcherTest {

    private PathMatcher pathMatcher = new AntPathMatcher();

    @Test
public void testQuestionMark() {
Assert.assertTrue(pathMatcher.match("config?.xml", "config1.xml"));
Assert.assertFalse(pathMatcher.match("config?.xml", "config12.xml"));
Assert.assertFalse(pathMatcher.match("config?.xml", "config.xml"));
} @Test
public void testOneAsterisk() {
Assert.assertTrue(pathMatcher.match("config-*.xml", "config-dao.xml"));
Assert.assertTrue(pathMatcher.match("config-*.xml", "config-.xml"));
Assert.assertTrue(pathMatcher.match("config-**.xml", "config-dao.xml")); Assert.assertFalse(pathMatcher.match("config-*.xml", "config-1/.xml"));
Assert.assertFalse(pathMatcher.match("config-*.xml", "config-1/2.xml")); Assert.assertTrue(pathMatcher.match("/cn/*/config.xml", "/cn/javass/config.xml")); Assert.assertFalse(pathMatcher.match("/cn/*/config.xml", "/cn/config.xml"));
Assert.assertFalse(pathMatcher.match("/cn/*/config.xml", "/cn//config.xml"));
Assert.assertFalse(pathMatcher.match("/cn/*/config.xml", "/cn/javass/spring/config.xml")); } @Test
public void testTwoAsterisk() {
Assert.assertTrue(pathMatcher.match("/cn/**/config-*.xml", "/cn/javass/config-dao.xml"));
Assert.assertTrue(pathMatcher.match("/cn/**/config-*.xml", "/cn/javass/spring/config-dao.xml"));
Assert.assertTrue(pathMatcher.match("/cn/**/config-*.xml", "/cn/config-dao.xml")); }
}

  

Spring在加载类路径资源时除了提供前缀“classpath:”的来支持加载一个Resource,还提供一个前缀“classpath*:”来支持加载所有匹配的类路径Resource。

Spring提供ResourcePatternResolver接口来加载多个Resource,该接口继承了ResourceLoader并添加了“Resource[] getResources(String locationPattern)”用来加载多个Resource:

public interface ResourcePatternResolver extends ResourceLoader {
String CLASSPATH_ALL_URL_PREFIX = "classpath*:";
Resource[] getResources(String locationPattern) throws IOException;
}

  

Spring提供了一个ResourcePatternResolver实现PathMatchingResourcePatternResolver,它是基于模式匹配的,默认使用AntPathMatcher进行路径匹配,它除了支持ResourceLoader支持的前缀外,还额外支持“classpath*:”用于加载所有匹配的类路径Resource,ResourceLoader不支持前缀“classpath*:”:

首先做下准备工作,在项目的“resources”创建“META-INF”目录,然后在其下创建一个“INDEX.LIST”文件。同时在“org.springframework.beans-3.0.5.RELEASE.jar”和“org.springframework.context-3.0.5.RELEASE.jar”两个jar包里也存在相同目录和文件。然后创建一个“LICENSE”文件,该文件存在于“com.springsource.cn.sf.cglib-2.2.0.jar”里。

一、“classpath”: 用于加载类路径(包括jar包)中的一个且仅一个资源;对于多个匹配的也只返回一个,所以如果需要多个匹配的请考虑“classpath*:”前缀;

@Test
public void testClasspathPrefix() throws IOException {
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
//只加载一个绝对匹配Resource,且通过ResourceLoader.getResource进行加载
Resource[] resources=resolver.getResources("classpath:META-INF/INDEX.LIST");
Assert.assertEquals(1, resources.length);
//只加载一个匹配的Resource,且通过ResourceLoader.getResource进行加载
resources = resolver.getResources("classpath:META-INF/*.LIST");
Assert.assertTrue(resources.length == 1);
}

  二、“classpath*”: 用于加载类路径(包括jar包)中的所有匹配的资源。带通配符的classpath使用“ClassLoader”的“Enumeration<URLgetResources(String name)”方法来查找通配符之前的资源,然后通过模式匹配来获取匹配的资源。如“classpath:META-INF/*.LIST”将首先加载通配符之前的目录“META-INF”,然后再遍历路径进行子路径匹配从而获取匹配的资源。

@Test
public void testClasspathAsteriskPrefix () throws IOException {
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
//将加载多个绝对匹配的所有Resource
//将首先通过ClassLoader.getResources("META-INF")加载非模式路径部分
//然后进行遍历模式匹配
Resource[] resources=resolver.getResources("classpath*:META-INF/INDEX.LIST");
Assert.assertTrue(resources.length > 1);
//将加载多个模式匹配的Resource
resources = resolver.getResources("classpath*:META-INF/*.LIST");
Assert.assertTrue(resources.length > 1);
}

  

注意“resources.length >1”说明返回多个Resource。不管模式匹配还是非模式匹配只要匹配的都将返回。

在“com.springsource.cn.sf.cglib-2.2.0.jar”里包含“asm-license.txt”文件,对于使用“classpath*: asm-*.txt”进行通配符方式加载资源将什么也加载不了“asm-license.txt”文件,注意一定是模式路径匹配才会遇到这种问题。这是由于“ClassLoader”的“getResources(String name)”方法的限制,对于name为“”的情况将只返回文件系统的类路径,不会包换jar包根路径。

@Test
public void testClasspathAsteriskPrefixLimit() throws IOException {
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(); //将首先通过ClassLoader.getResources("")加载目录,
//将只返回文件系统的类路径不返回jar的跟路径
//然后进行遍历模式匹配
Resource[] resources = resolver.getResources("classpath*:asm-*.txt");
Assert.assertTrue(resources.length == 0);
//将通过ClassLoader.getResources("asm-license.txt")加载
//asm-license.txt存在于com.springsource.net.sf.cglib-2.2.0.jar
resources = resolver.getResources("classpath*:asm-license.txt");
Assert.assertTrue(resources.length > 0);
//将只加载文件系统类路径匹配的Resource
resources = resolver.getResources("classpath*:LICENS*");
Assert.assertTrue(resources.length == 1);
}

  

对于“resolver.getResources("classpath*:asm-*.txt");”,由于在项目“resources”目录下没有所以应该返回0个资源;“resolver.getResources("classpath*:asm-license.txt");”将返回jar包里的Resource;“resolver.getResources("classpath*:LICENS*");”,因为将只返回文件系统类路径资源,所以返回1个资源。

因此加载通配符路径时(即路径中包含通配符),必须包含一个根目录才能保证加载的资源是所有的,而不是部分。

三、“file”:加载一个或多个文件系统中的Resource。如“file:D:/*.txt”将返回D盘下的所有txt文件;

四、无前缀:通过ResourceLoader实现加载一个资源。

AppliacationContext提供的getResources方法将获取资源委托给ResourcePatternResolver实现,默认使用PathMatchingResourcePatternResolver。所有在此就无需介绍其使用方法了。

4.4.2  注入Resource数组

Spring还支持注入Resource数组,直接看配置如下:

<bean id="resourceBean1" class="cn.javass.spring.chapter4.bean.ResourceBean4">
<property name="resources">
<array>
<value>cn/javass/spring/chapter4/test1.properties</value>
<value>log4j.xml</value>
</array>
</property>
</bean>
<bean id="resourceBean2" class="cn.javass.spring.chapter4.bean.ResourceBean4">
<property name="resources" value="classpath*:META-INF/INDEX.LIST"/>
</bean>
<bean id="resourceBean3" class="cn.javass.spring.chapter4.bean.ResourceBean4">
<property name="resources">
<array>
<value>cn/javass/spring/chapter4/test1.properties</value>
<value>classpath*:META-INF/INDEX.LIST</value>
</array>
</property>
</bean>

  

“resourceBean1”就不用多介绍了,传统实现方式;对于“resourceBean2”则使用前缀“classpath*”,看到这大家应该懂的,加载匹配多个资源;“resourceBean3”是混合使用的;测试代码在“cn.javass.spring.chapter4.ResourceInjectTest.testResourceArrayInject”。

Spring通过ResourceArrayPropertyEditor来进行类型转换的,而它又默认使用“PathMatchingResourcePatternResolver”来进行把路径解析为Resource对象。所有大家只要会使用“PathMatchingResourcePatternResolver”,其它一些实现都是委托给它的,比如AppliacationContext的“getResources”方法等。

4.4.3  AppliacationContext实现对各种Resource的支持

一、ClassPathXmlApplicationContext默认将通过classpath进行加载返回ClassPathResource,提供两类构造器方法:

public class ClassPathXmlApplicationContext {
//1)通过ResourcePatternResolver实现根据configLocation获取资源
public ClassPathXmlApplicationContext(String configLocation);
public ClassPathXmlApplicationContext(String... configLocations);
public ClassPathXmlApplicationContext(String[] configLocations, ……); //2)通过直接根据path直接返回ClasspathResource
public ClassPathXmlApplicationContext(String path, Class clazz);
public ClassPathXmlApplicationContext(String[] paths, Class clazz);
public ClassPathXmlApplicationContext(String[] paths, Class clazz, ……);
}

  

第一类构造器是根据提供的配置文件路径使用“ResourcePatternResolver ”的“getResources()”接口通过匹配获取资源;即如“classpath:config.xml”

第二类构造器则是根据提供的路径和clazz来构造ClassResource资源。即采用“public ClassPathResource(String path, Class<?> clazz)”构造器获取资源。

       二、FileSystemXmlApplicationContext将加载相对于当前工作目录的“configLocation”位置的资源,注意在linux系统上不管“configLocation”是否带“/”,都作为相对路径;而在window系统上如“D:/resourceInject.xml”是绝对路径。因此在除非很必要的情况下,不建议使用该ApplicationContext。

public class FileSystemXmlApplicationContext{
public FileSystemXmlApplicationContext(String configLocation);
public FileSystemXmlApplicationContext(String... configLocations,……);
}

  

//linux系统,以下全是相对于当前vm路径进行加载
new FileSystemXmlApplicationContext("chapter4/config.xml");
new FileSystemXmlApplicationContext("/chapter4/confg.xml");

  

//windows系统,第一个将相对于当前vm路径进行加载;
//第二个则是绝对路径方式加载
new FileSystemXmlApplicationContext("chapter4/config.xml");
new FileSystemXmlApplicationContext("d:/chapter4/confg.xml");

   此处还需要注意:在linux系统上,构造器使用的是相对路径,而ctx.getResource()方法如果以“/”开头则表示获取绝对路径资源,而不带前导“/”将返回相对路径资源。如下:

//linux系统,第一个将相对于当前vm路径进行加载;
//第二个则是绝对路径方式加载
ctx.getResource ("chapter4/config.xml");
ctx.getResource ("/root/confg.xml");
//windows系统,第一个将相对于当前vm路径进行加载;
//第二个则是绝对路径方式加载
ctx.getResource ("chapter4/config.xml");
ctx.getResource ("d:/chapter4/confg.xml");

   因此如果需要加载绝对路径资源最好选择前缀“file”方式,将全部根据绝对路径加载。如在linux系统“ctx.getResource ("file:/root/confg.xml");”

spring3: 4.4 使用路径通配符加载Resource的更多相关文章

  1. Java使用路径通配符加载Resource与profiles配置使用

    序言 Spring提供了一种强大的Ant模式通配符匹配,能从一个路径匹配一批资源. Ant路径通配符 Ant路径通配符支持“?”.“*”.“**”,注意通配符匹配不包括目录分隔符“/”: “?”:匹配 ...

  2. UNITY_资源路径与加载外部文件

    UNITY_资源路径与加载外部文件 https://www.tuicool.com/articles/qMNnmm6https://blog.csdn.net/appppppen/article/de ...

  3. Spring的 classpath 通配符加载配置文件

    http://www.cnblogs.com/taven/archive/2012/10/24/2737556.html classpath:app-Beans.xml 说明:无通配符,必须完全匹配 ...

  4. Keras.applications.models权重:存储路径及加载

    网络中断原因导致keras加载vgg16等模型权重失败, 直接解决方法是:删掉下载文件,再重新下载 Windows-weights路径: C:\Users\你的用户名\.keras\models Li ...

  5. Unity资源加载路径及加载方式小结

    Unity3D中的资源路径路径属性 路径说明Application.dataPath 此属性用于返回程序的数据文件所在文件夹的路径.例如在Editor中就是Assets了.Application.st ...

  6. SSM项目使用junit单元测试时Mybaties通配符加载Mapper不能正常加载

    个人博客 地址:http://www.wenhaofan.com/article/20181108104133 问题描述 项目使用maven build 以及tomcat run能够正常运行,但是使用 ...

  7. 【转载】Spring加载resource时classpath*:与classpath:的区别

    免责声明:     本文转自网络文章,转载此文章仅为个人收藏,分享知识,如有侵权,请联系博主进行删除.     原文作者:kyfxbl     原文地址: spring配置中classpath和cla ...

  8. 05.Spring 资源加载 - Resource

    基本概念 Spring 把所有能记录信息的载体,如各种类型的文件.二进制流等都称为资源. 对 Spring 开发者来说,最常用的资源就是 Spring 配置文件(通常是一份 XML 格式的文件). S ...

  9. Photon自定义加载Resource之外的资源

    PhotonNetwork.cs 结尾添加如下代码: #region >>> Photon自定义异步加载GameObject public delegate void CustomL ...

随机推荐

  1. 在.NET中读取嵌入和使用资源文件的方法

    转http://www.jb51.net/article/84660.htm 本文分别介绍了使用GetManifestResourceStream读取嵌入资源,和使用. resx资源文件嵌入资源,希望 ...

  2. Java 集合框架之 JDK 1.5 新特性

    forEach 循环 多用于元素迭代. 适用范围: - 数组 - 实现 Iterable 接口的集合类 格式: for(类型 变量 : Collection 集合 | 数组) { } 传统 for 和 ...

  3. MySQL 如何利用一条语句实现类似于if-else条件语句的判断

    一. 编写一条update语句实现商品涨价,具体规则如下 1.99元以内,提价20% 2.100-999元之间,提价10% 3.1000-1999之间,提价5% 4.其他提价2% update goo ...

  4. netstat命令——网络,进程,内存

    netstat网络.进程.内存 转自:https://www.cnblogs.com/xieshengsen/p/6618993.html https://zhidao.baidu.com/quest ...

  5. io.Writer

    var w io.Writer // 设置为你的 io.Writer var b bytes.Buffer fmt.Fprint(&b, "Hello World") w ...

  6. Webbench进行网站压力测试

    今天突然发现一个新大陆,Webbench,是linux下,用这很方便,开源,不限制并发访问次数和时间....大爱啊! 下载Webbench 使用wget  或者windows下载好导入linux也行, ...

  7. 使用Ehcache缓存同步启动时抛出异常net.sf.ehcache.CacheException: Can't assign requested address

    这个问题在插入公司内网网线的时候不会复现,由于我使用的是公司无线网络,故导致此问题. 具体解决办法是:在启动服务时,指定使用默认ipv4的网络接口.可以在启动jvm时添加参数-Djava.net.pr ...

  8. 用python简便地抓取刘昊然的写真(17行代码)

    17行python代码抓取刘昊然图片之家的写真 用python来爬取网页信息是很简便的.因为它有很多库来帮助我们实现我们想要的功能.本实验用到的库有:requests和bs4中的BeautifulSo ...

  9. python s12

    logging模块 很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误.警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式 ...

  10. Python(模块(modue)、包(package))

    ''' 一 模块 模块一共三种: python标准库 第三方模块 应用程序自定义模块 模块两种执行方式: 1 用于启动执行 2 用于被调用执行 key:import module: 将执行文件(mod ...