Spring获取资源方式

1.1.1.1.ClassPathXmlApplicationContext

ClassPathXmlApplicationContext支持从classpath中查找资源。假如我以下面的方式启动Spring

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");

那么系统将会从classpath中查找myFile.xml文件。相当于:

URL resource = getClassLoader().getResource("myFile.xml");

1.1.1.2.FileSystemXmlApplicationContext

FileSystemXmlApplicationContext支持从文件系统中查找资源。假如我以下面的方式启动Spring

ApplicationContext context = new FileSystemXmlApplicationContext("beans.xml");

那么系统将会在文件系统中查找myFile.xml文件。相当于:

File resource = new File("myFile.xml");

1.1.1.3.XmlWebApplicationContext

XmlWebApplicationContext支持从webapp上下文中(也就是ServletContext对象中)查找资源。假如我以下面的方式启动Spring

ApplicationContext context = new XmlWebApplicationContext();

或者在/WEB-INF/web.xml中添加如下配置:

<context-param>

    <param-name>contextConfigLocation</param-name>

    <param-value>/WEB-INF/beans.xml</param-value>

</context-param>

<listener>

    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

</listener>

那么系统将会在Web应用的根目录中查找myFile.xml。相当于:

URL resource = servletContext.getResource("myFile.xml");

1.1.1.4.ClasspathClasspath*前缀

除了用ClassPathXmlApplicationContext来装载classpath下的资源,所有的Spring ApplicationContext实现都支持从classpath中装载资源:

l  使用classpath前缀:“classpath:myFile.xml —— classpath中查找资源myFile.xml

l  使用classpath*前缀:“classpath*:/META-INF/my*.xml —— classpath中查找所有符合pattern的资源。

1.1.2.Spring ResourceLoader的缺点

l  鱼和熊掌不可得兼

Spring ResourceLoader是由ApplicationContext来实现的。而你一次只能选择一种ApplicationContext的实现 —— 如果你选择了XmlWebApplicationContext,你就放弃了FileSystemXmlApplicationContext;反之亦然。

WEB应用中,由于Spring使用了XmlWebApplicationContext,因此你就无法装载文件系统下的资源。

l  不透明性

你必须用“绝对路径”来引用Spring中的资源。

假如你使用FileSystemXmlApplicationContext来访问资源,你必须使用绝对路径来访问文件或目录资源。这妨碍了应用程序在不同系统中布署的自由。因为在不同的系统中,例如WindowsLinux,文件的绝对路径是不同的。为了系统管理的需要,有时也需要将文件或目录放在不同于开发环境的地方。

即便是访问WEB应用下的资源,或者是classpath下的资源,你也必须明确指出它们的位置,例如:WEB-INF/myFile.xmlclasspath:myFile.xml等。如果我希望把classpath:myFile.xml挪到另一个物理位置,就必须修改所有的引用。

l  无扩展性

我无法在Spring ResourceLoader机制中增加一种新的装载资源的方法。例如,我希望把资源文件保存在数据库中,并用ResourceLoader来取得它。

 


本文转自 zhouhaipeng 51CTO博客,原文链接:http://blog.51cto.com/tianya23/695352,如需转载请自行联系原作者


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值