ITeye博客

配置文件读取

cping · 2014-04-30 16:57 · web应用 · Web前端 · Markdown

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

			
<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暴露出去了。

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


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

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

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。