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类。

  • 相关阅读:
    SQL注入原理
    攻防世界-wp
    BUUCTF-warmup
    springboot邮箱验证功能部署到服务器后报25 timeout的解决方式
    关于MySQL建立库表时大写自动转换为小写的解决方案
    springboot格式化timestamp时间
    mysql高级查询
    pip更新一直time out 的解决方法
    关于springboot使用mybatis查询出现空指针,以及debug出现All Elements all Null的解决方法
    抽象工厂模式
  • 原文地址:https://www.cnblogs.com/wuxun1997/p/7099216.html
Copyright © 2011-2022 走看看