spring使用外部属性文件

来源:互联网 发布:b站mac客户端 编辑:程序博客网 时间:2024/06/10 23:44

在配置文件里配置Bean时,有时需要在Bean的配置里混入系统部署的细节信息(eg : 文件路径,数据源配置信息)而这些部署细节实际上需要和Bean配置相分离。
Spring的资源加载器提供了一个统一的getResource()方法,使用这个方法可以通过资源路径获取外部资源,可以给路径指定不同的前缀以从不同位置加载资源。(eg:要从文件系统加载资源,可以使用file前缀,要从classpath加载资源,可以使用classpath前缀,也可以在这个资源路径里指定URL。)
Resource是Spring里的一个通用接口,它代表了一个外部资源。Spring为Resource接口提供了几种实现。资源加载器的getResource()方法将根据资源路径决定实例化哪一个Resource实现。
1.文件系统路径:
资源路径可以使用文件系统的相对路径,也可以使用绝对路径。
file:c:/file/txt.txt

2.classpath类路径
当资源位于classpath时,可以使用classpath前缀。如果没有出现路径信息,那么将从classpath的根部加载资源。
classpath:txt.txt

3.除了文件系统路径和classpath外,资源也可以通过指定URL加载。
http://springrecipes.apress.com/shop/banner.txt

在Bean的配置里,简单地为Resource属性指定一个资源路径。Spring将使用预先注册的属性编辑器ResourceEditor将
资源转换为Resource对象,然后,再将该Resource对象注入到Bean里。

配置文件加载的两种方式
第一种:

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">      <property name="locations">          <list><value>classpath:config.properties</value></list>      </property></bean>

第二种:需要引入带如下 * 号内的代码

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    ***xmlns:context="http://www.springframework.org/schema/context"***    xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans.xsd        ***http://www.springframework.org/schema/context        http://www.springframework.org/schema/context/spring-context.xsd***        ">    //扫描注释    <context:component-scan base-package="cn"></context:component-scan>    //配置文件加载    <context:property-placeholder location="classpath:jdbc.properties"/></beans>
原创粉丝点击