码迷,mamicode.com
首页 > 移动开发 > 详细

Spring MVC框架下在java代码中访问applicationContext.xml文件中配置的文件(可以用于读取配置文件内容)

时间:2015-10-19 16:52:07      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:

<bean id="propertyConfigurer" class="com.****.framework.core.SpringPropertiesUtil"
        lazy-init="false">
        <property name="locations">
            <list>
                <value>classpath:config/sys.properties</value>
            </list>
        </property>
    </bean>

applicationContext.xml文件中配置好sys.properties文件的路径 ↑↑↑↑

然后是springPropertiesUtil文件内容:

package com.****.framework.core;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;

import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class SpringPropertiesUtil extends PropertyPlaceholderConfigurer {

    private static Map<String, String> propertiesMap;
    // Default as in PropertyPlaceholderConfigurer
    private int springSystemPropertiesMode = SYSTEM_PROPERTIES_MODE_FALLBACK;

    @Override
    public void setSystemPropertiesMode(int systemPropertiesMode) {
        super.setSystemPropertiesMode(systemPropertiesMode);
        springSystemPropertiesMode = systemPropertiesMode;
    }

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties props) throws BeansException {
        super.processProperties(beanFactory, props);

        propertiesMap = new HashMap<String, String>();
        for (Object key : props.keySet()) {
            String keyStr = key.toString();
            String valueStr = resolvePlaceholder(keyStr, props, springSystemPropertiesMode);
            propertiesMap.put(keyStr, valueStr);
        }
    }
    public static String getProperty(String name) {
        return propertiesMap.get(name).toString();
    }
    
    public static String getProperty(String name,String def) {
        String ret = propertiesMap.get(name);
        if(StringUtils.isBlank(ret)){
            return def;
        }
        return ret.toString();
    }

}

第三步是正题:在java代码中调用这个配置:

 SpringPropertiesUtil springPropertiesUtil = (SpringPropertiesUtil) applicationContext.getBean("propertyConfigurer");
            return springPropertiesUtil.getProperty(key);

 

Spring MVC框架下在java代码中访问applicationContext.xml文件中配置的文件(可以用于读取配置文件内容)

标签:

原文地址:http://www.cnblogs.com/ning-blogs/p/4892002.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!