spring以外部化Bean配置

spring之外部化Bean配置

spring之外部化Bean配置

----------

 

在配置文件里配置Bean时,必须牢记在Bean的配置里混入系统部署的细节信息并不是好的做法。这些信息包括文件路径、服务器地址、用户名以及密码。通常,应用程序开发人员负责编写Bean的配置,而部署人员或者系统管理员负责管理系统部署的细节。

Spring提供了一个叫做PropertyPlaceholderConfigurer的Bean Factory后置处理器,这个处理器允许用户将Bean配置的部分内容外部化到属性文件里。可以在Bean配置文件里使用形式为${var}的变量,PropertyPlaceholderConfigurer将从属性文件里加载属性,并使用这些属性来替换变量

如例:

<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
	<property name="location">
		<value>config.properties</value>
	</property>
</bean>
作为Bean Factory后置处理器,PropertyPlaceholderConfigurer将会在Bean被实例化之前用外部的属性替换掉Bean配置文件里的相应变量。

Spring2.5里,可以通过<context:property-placeholder>元素简化PropertyPlaceholderConfigurer的注册。

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns:context="http://www.springframeork.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-2.5.xsd">
		
	<context:property-placeholder location="config.propertis"/>
	...
</beans>