---
title: "配置文件读取"
author: "cping"
date: "2014-04-30T16:57:48Z"
tags: []
categories: ["Web前端"]
slug: "untitled"
draft: false
lastmod: "2015-01-21T11:23:07Z"
id: 2058945
url: "https://cping.iteye.com/blog/2058945"
---

配置文件放在工程外，可以采取下面的方式：


```xml
			
<value>
					file:${user.dir}/config/service/global-config.properties
				</value>
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>file:${user.dir}/config/service/log4j-default.xml</param-value>
	</context-param>
```

如果是tomcat，就是在tomcat的bin目录下。

      也可以通过编程方式取得Spring上下文的Properties，继承PropertyPlaceholderConfigurer，通过重写processProperties方法把properties暴露出去了。

```java

public class CustomizedPropertyConfigurer extends PropertyPlaceholderConfigurer {  
  
    private static Map<String, Object> ctxPropertiesMap;  
  
    @Override  
    protected void processProperties(ConfigurableListableBeanFactory beanFactory,  
            Properties props)throws BeansException {  
  
        super.processProperties(beanFactory, props);  
        //load properties to ctxPropertiesMap  
        ctxPropertiesMap = new HashMap<String, Object>();  
        for (Object key : props.keySet()) {  
            String keyStr = key.toString();  
            String value = props.getProperty(keyStr);  
            ctxPropertiesMap.put(keyStr, value);  
        }  
    }  
  
    //static method for accessing context properties  
    public static Object getContextProperty(String name) {  
        return ctxPropertiesMap.get(name);  
    }  
}  

```

这样此类即完成了PropertyPlaceholderConfigurer的任务，同时又提供了上下文properties访问的功能。
于是在Spring配置文件中把PropertyPlaceholderConfigurer改成CustomizedPropertyConfigurer

```xml

<bean id="configBean"   
    class="com.**.util.CustomizedPropertyConfigurer">  
    <property name="location" value="classpath:dataSource.properties" />  
</bean>  

```

最后在程序中我们便可以使用CustomizedPropertyConfigurer.getContextProperty()来取得上下文中的properties的值了。