zoukankan      html  css  js  c++  java
  • Spring读取properties资源文件

      我们知道可以通过读取资源文件流后加载到Properties对象,再使用该对象方法来获取资源文件。现在介绍下利用Spring内置对象来读取资源文件。

      系统启动时加载资源文件链路:web.xml -->  spring-core.xml --> sysconfig.properties

      接下来直接看代码吧

    web.xml

        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-core.xml</param-value>
        </context-param>

    spring-core.xml

        <!-- 加载properties里的内容 -->
        <bean id="PropertyConfig" class="com.wulinfeng.PropertiesConfig">
            <property name="ignoreUnresolvablePlaceholders" value="true" />
            <property name="locations">
                <list>               
                    <value>classpath:sysconfig.properties</value>
                </list>
            </property>
            <property name="fileEncoding">
                <value>UTF-8</value>
            </property>
        </bean>
    PropertiesConfig.java
    public class PropertiesConfig extends PropertyPlaceholderConfigurer
    {
        private static Map<String, String> propertyMap;
        
        @Override
        protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
            throws BeansException
        {
            super.processProperties(beanFactoryToProcess, props);
            if (propertyMap == null || propertyMap.size() == 0)
            {
                propertyMap = new HashMap<String, String>();
                
                for (Object key : props.keySet())
                {
                    String keyStr = key.toString();
                    String value = props.getProperty(keyStr);
                    propertyMap.put(keyStr, value);
                }
            }
        }
        
        public static String getProperty(String name,String def)
        {
            if (propertyMap == null || propertyMap.isEmpty() || null == propertyMap.get(name))
            {
                return def;
            }
            return propertyMap.get(name);
        }
        
        public static String getProperty(String name)
        {
            if (propertyMap == null || propertyMap.isEmpty())
            {
                return null;
            }
            return propertyMap.get(name);
        }
        
    }

      注意这里需要继承Spring的PropertyPlaceholderConfigurer类。

  • 相关阅读:
    学习Android有感!
    使用PHP-Barcode轻松生成条形码(一)
    php利用redis实现分页列表,新增,删除功能
    JS验证input输入框(字母,数字,符号,中文)正则实现
    mac 安装swoole扩展
    git 配置本地SSH秘钥
    lnmp 一键安装
    lnmp php版本升级
    NATAPP内网穿透,本地进行微信开发,支付开发,对象存储回调信息
    微信公众号二维码
  • 原文地址:https://www.cnblogs.com/wuxun1997/p/7099216.html
Copyright © 2011-2022 走看看