---
title: "spring的applicationContext.xml中使用属性文件*.properties"
author: "duyunfengsolo"
date: "2009-08-21T15:46:38Z"
tags: ["Bean", "JDBC", "PostgreSQL", "Spring", "XML"]
slug: "spring-applicationcontext-xml-properties"
draft: false
lastmod: "2009-08-21T15:46:38Z"
id: 454538
url: "https://solodu.iteye.com/blog/454538"
---

我们可以生成如下的属性文件（/WEB-INF/jdbc.properties）：

jdbc.driver=org.postgresql.Driver  
jdbc.url=jdbc:postgresql://localhost/test  
jdbc.user=postgres  
jdbc.password=

　　我们的Bean配置如下：

&lt;bean id="propertyConfigurer"  
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"&gt;  
    &lt;property name="location"&gt;  
       &lt;value&gt;/WEB-INF/jdbc.properties&lt;/value&gt;  
    &lt;/property&gt;  
&lt;/bean&gt;

&lt;bean id="dataSource"  
class="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt;  
    &lt;property name="driverClassName"&gt;  
         &lt;value&gt;${jdbc.driver}&lt;/value&gt;  
    &lt;/property&gt;  
    &lt;property name="url"&gt;  
         &lt;value&gt;${jdbc.url}&lt;/value&gt;  
    &lt;/property&gt;  
    &lt;property name="username"&gt;  
         &lt;value&gt;${jdbc.user}&lt;/value&gt;  
    &lt;/property&gt;  
    &lt;property name="password"&gt;  
         &lt;value&gt;${jdbc.password}&lt;/value&gt;  
    &lt;/property&gt;  
&lt;/bean&gt;

　　如上所述，我们定义了一个PropertyPlaceholderConfigurer类的实例，并将其位置属性设置为我们的属性文件。该类被实现为Bean工厂的后处理器，并将使用定义在文件中的属性来代替所有的占位符（${...}value）。

　　利用这种技术，我们可以从applicationContext.xml中移除所有特定于主机的配置属性。通过这种方式，我们可以自由地为该文件添加新的Bean，而不必担心特定于主机属性的同步性。这样可以简化生产部署和维护。