`
DXL_xiaoli
  • 浏览: 69603 次
  • 性别: Icon_minigender_2
  • 来自: 北京
社区版块
存档分类
最新评论

体验spring(八)---分散配置

阅读更多

分散配置

在应用上下文中,使用PropertyPlaceholderConfigurer从外部文件装载配置信息。其中location属性允许使用单个配置文件,可使用其locations属性设置配置文件列表。

案例:
Service包中ConnServiceImpl.java
public class ConnServiceImpl {
	/*连接数据库**/
private String driverClass;
private String url;
private String user;
private String password;
public void setDriverClass(String driverClass) {
	this.driverClass = driverClass;
}
public void setUrl(String url) {
	this.url = url;
}
public void setUser(String user) {
	this.user = user;
}
public void setPassword(String password) {
	this.password = password;
}

}
Jdbc.properties文件
jdbc\:driverClass=com.mysql.jdbc.Driver
jdbc\:url=jdbc\:mysql\://localhost\:3306/db
jdbc\:user=dxl
jdbc\:password=root
applicationContext.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
           
    <!-- 分散配置解析 引入一个外部文件即使用location属性       
	<bean id="propertyPlaceholderConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="location">
			<value>cn/csdn/service/jdbc.properties</value>
		</property>		
	</bean>
	--> 
	<!-- 其中location属性允许使用单个配置文件,可使用其locations属性设置配置文件列表。classPath使用反斜杠
	使用分散配置就可用占位符变量替代Bean配置文件中硬编码配置了,语法上,占位符变量采用${variable}形式	
	 -->
	
	<!-- 引入多个外部文件即使用locations属性 -->
	<bean id="propertyPlaceholderConfigurer"
		class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
		<property name="locations">
			<value>cn/csdn/service/jdbc.properties</value>
		</property>		
	</bean>
	
	<bean id="connServiceImpl" class="cn.csdn.service.ConnServiceImpl"
		scope="singleton">
		<property name="driverClass">
		<!-- 在使用外部文件的名称方式${名称} -->
			<value>${jdbc:driverClass}</value>
		</property>

		<property name="url">
			<value>${jdbc:url}</value>
		</property>

		<property name="user">
			<value>${jdbc:user}</value>
		</property>

		<property name="password">
			<value>${jdbc:password}</value>
		</property>
	</bean>
	
	<!-- 硬编码 的使用
	<bean id="connServiceImpl" class="cn.csdn.service.ConnServiceImpl"
		scope="singleton">
		<property name="driverClass">
			<value>com.mysql.jdbc.Driver</value>
		</property>

		<property name="url">
			<value>jdbc:mysql://localhost:3306/db</value>
		</property>

		<property name="user">
			<value>dxl</value>
		</property>

		<property name="password">
			<value>root</value>
		</property>
	</bean>
-->
</beans>

 

此案例中主要介绍了分散配置的使用,首先介绍了硬编码的使用,然后是引入单个分散配置的使用,再就是引入多个分散配置的使用,并将三者做了具体的比较。读者主要观察xml文件中的代码,xml文件中的代码简单明了,易于理解。

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics