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

    <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);
  • 相关阅读:
    leetcode78 Subsets
    leetcode76 Minimum Window Substring
    leetcode73 Set Matrix Zeroes
    leetcode70 Climbing Stairs
    leetcode50 Pow(x, n)
    leetcode49 Group Anagrams
    leetcode48 Rotate Image
    正则表达式及字符处理
    RPM软件包管理.作业
    yum管理RPM包.作业
  • 原文地址:https://www.cnblogs.com/ning-blogs/p/4892002.html
Copyright © 2011-2022 走看看