六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 248|回复: 0

Spring中配置属性的外在化

[复制链接]

升级  84%

8

主题

8

主题

8

主题

童生

Rank: 1

积分
42
 楼主| 发表于 2013-1-14 23:42:52 | 显示全部楼层 |阅读模式
大多数情况下,我们可以在一个Bean装配文件里配置整个程序,但有的时候却需要把部分配置提取到单独的属性文件中,最常见的一种情形就是配置数据源。
 
在Spring里,如果使用ApplicationContext作为Spring容器(另一种是使用BeanFactory,ApplicationContext提供了更多的功能,所以大部分都是使用ApplicationContext作为Spring容器),属性的外在化就很容易,开发者可以使用Spring的PropertyPlaceholderConfigurer告诉Spring从外部属性文件加载特定的配置。为了启用这个特性,需要在Bean装配文件里配置如下的Bean:
  
 
<bean id="propertyConfigurer"           class="org.springframework.beans.factory.config. PropertyPlaceholderConfigurer">    <property name="location" value="jdbc.properties"/><!-- value的按照具体情况取值--> </bean> loaction属性告诉Spring到哪里寻找属性文件。在本例中jdbc.properties文件中包含以下内容:
database.url=jdbc:hsqldb:Trainingdatabase.driver=org.hsqldb.jdbc.jdbcDriverdatabase.user=rootdatabase.paseword=password 
location属性可以处单个属性文件。如果需要把配置分散到多个属性文件中,应该使用PropertyPlaceholderConfigurer的locations(注意加了一个“s”)属性来设置属性文件的List。配置文件如下:
<bean id="propertyConfigurer"           class="org.springframework.beans.factory.config. PropertyPlaceholderConfigurer">    <property name="locations">          <list>                <value>jdbc.properties</value>                <value>security.properties</value>                <value>application.properties</value>          </list>      </property> </bean> 
 
经过上述配置后,我们就可以在Bean装配文件里用占位变量代替硬编码的配置。从语法来说,占位变量的形式是${variable}。在使用占位变量之后,dataSource Bean的声明会是这样:
<bean id="datasource"            class="org.springframework.jdbc.datasource.DriveManagerDataSource"><!--这种方式是基于JDBC驱动定义的数据源-->     <property name="url" value="${database.url}"/>     <property name="driverClassName"                    value="${database.driver}"/>     <property name="username" value="${database.user}"/>     <property name="passeord" value="${database.passeord}"/></bean> 当Spring创建dataSource Bean时,PropertyPlaceholderConfigurer会介入并用属性文件里的值替换占位变量。
 
     如附件中图所示 
 
 除了配置文件外,PropertyPlaceholderConfigurer还经常用于保存文本消息和实现国际化
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表