---
title: "spring 读取properties配置文件"
author: "siser344"
date: "2010-07-15T22:40:13Z"
tags: []
categories: ["企业架构"]
slug: "spring-properties"
draft: false
lastmod: "2010-07-15T22:40:13Z"
id: 713901
url: "https://siser344.iteye.com/blog/713901"
---

在Spring中，使用PropertyPlaceholderConfigurer和PropertyOverrideConfigurer可以在XML配置文件中加入外部属性文件  
但使用这种方式，有一些需要注意的地方

1.首先在主类中，需要使用ClassPathXmlApplicationContext来读取spring配置xml文件  
如：

ApplicationContext context = new ClassPathXmlApplicationContext("example4/appcontext.xml");  
HelloWorld hw = (HelloWorld)context.getBean("fileHelloWorld");  
log.info(hw.getContent());

直接以beanFactory方式，是无法使用PropertyPlaceholderConfigurer或PropertyOverrideConfigurer的  
如下方式不行：  
Resource resource = new ClassPathResource("example4/appcontext.xml");  
BeanFactory factory = new XmlBeanFactory(resource);  
HelloWorld hw = (HelloWorld) factory.getBean("fileHelloWorld");  
log.info(hw.getContent());

2.PropertyOverrideConfigurer需要考虑bean的名称  
如下是正确配置：  
appcontext.xml:  
&lt;bean name="fileHelloWorld" class="example4.HelloWorld"&gt;  
    &lt;constructor-arg&gt;  
        &lt;ref bean="fileHello"/&gt;  
    &lt;/constructor-arg&gt;  
    &lt;property name="statusname"&gt;  
        &lt;value&gt;${fileHelloWorld.statusname}&lt;/value&gt;  
    &lt;/property&gt;  
&lt;/bean&gt;

&lt;bean id="propertyConfigurer"  
      class="org.springframework.beans.factory.config.PropertyOverrideConfigurer"&gt;  
    &lt;property name="location" value="classpath:example4/helloworld.properties"/&gt;  
&lt;/bean&gt;

helloworld.properties:  
fileHelloWorld.statusname=this is status Name;

如果少了${fileHelloWorld.statusname}中少了Bean名称fileHelloWorld，会导致错误发生  
这应该是种强制某个配置是属性某个Bean

3.PropertyPlaceholderConfigurer的配置不需要考虑Bean的名称，直接配置就可以了  
配置方式和PropertyOverrideConfigurer类似，如下配置：

```
<bean id= "propertyConfigurer"          
        class = "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >          
    <property name="location"  value= "/WEB-INF/jdbc.properties" />          
</bean>          
<bean id="dataSource"   class = "org.apache.commons.dbcp.BasicDataSource"            
        destroy-method="close" >          
    <property name="driverClassName"  value= "${jdbc.driverClassName}"  />          
    <property name="url"  value= "${jdbc.url}"  />          
    <property name="username"  value= "${jdbc.username}"  />          
    <property name="password"  value= "${jdbc.password}"  />          
</bean>       
   
    在jdbc.properties属性文件中定义属性值：    
    jdbc.driverClassName= com.mysql.jdbc.Driver    
    jdbc.url= jdbc:mysql://localhost:3309/sampledb     
    jdbc.username=root    
 jdbc.password=1234     
```