有时,应用程序可能需要从不同的位置(例如:文件系统、classpath或者URL)读取外部资源(例如:文本文件、xml文件、属性文件或或者图像文件)。通常,为了从不同位置加载资源,需要和不同的API打交道。
Spring的资源加载器提供了一个统一的getResource()方法,使用这个方法可以通过资源路径获取外部资源。可以给路径指定不同的前缀以从不同位置加载资源。要从文件系统加载资源,可以使用file前缀,要从classpath加载资源,可以使用classpath前缀,也可以在这个资源路径里指定URL。
Resource是Spring里的一个通用接口,它代表了一个外部资源。Spring为Resource接口提供了几种实现。资源加载器的getResource()方法将根据资源路径决定实例化哪一个Resource实现。
1.文件系统路径
资源路径可以使用文件系统的相对路径,也可以使用绝对路径。
file:c:/shop/banner.txt
加载d盘下的文件
<bean id="app-messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>file:d:/opt/lt/xg/cfg/commonconfigure</value>
<value>file:d:/opt/lt/xg/cfg/messages</value>
<value>file:d:/opt/lt/xg/cfg/config/config</value>
</list>
</property>
<property name="defaultEncoding">
<value>UTF-8</value>
</property>
</bean>
2.classpath路径
当资源位于classpath时,可以使用classpath前缀。如果没有出现路径信息,那么将从classpath的根部加载资源。
classpath:banner.txt
<context:property-placeholder location="classpath:db.properties"/>
3.除了文件系统路径和classpath外,资源也可以通过指定URL加载。
http://springrecipes.apress.com/shop/banner.txt
在Bean的配置里,简单地为Resource属性指定一个资源路径。Spring将使用预先注册的属性编辑器ResourceEditor将
资源转换为Resource对象,然后,再将该Resource对象注入到Bean里。
<bean id="bannerLoader" class="com.apress.springrecipes.shop.BannerLoader"
init-method="showBanner">
<property name="banner">
<value>classpath:com/apress/springrecipes/shop/banner.txt</value>
</property>
</bean>