Spring中配备属性的外在化
Spring中配置属性的外在化
大多数情况下,我们可以在一个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:Training database.driver=org.hsqldb.jdbc.jdbcDriver database.user=root database.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还经常用于保存文本消息和实现国际化