• (转)Spring用代码来读取properties文件


    转至http://www.cnblogs.com/Gyoung/p/5507063.html

    我们都知道,Spring可以@Value的方式读取properties中的值,只需要在配置文件中配置org.springframework.beans.factory.config.PropertyPlaceholderConfigurer

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
            <property name="location">
                <value>classpath:config.properties</value>
            </property>
        </bean>

    那么在需要用到这些获取properties中值的时候,可以这样使用

        @Value("${sql.name}")
        private String sqlName;

    但是这有一个问题,我每用一次配置文件中的值,就要声明一个局部变量。有没有用代码的方式,直接读取配置文件中的值。

    答案就是重写PropertyPlaceholderConfigurer

    复制代码
    public class PropertyPlaceholder extends PropertyPlaceholderConfigurer {
    
        private static Map<String,String> propertyMap;
    
        @Override
        protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props) throws BeansException {
            super.processProperties(beanFactoryToProcess, props);
            propertyMap = new HashMap<String, String>();
            for (Object key : props.keySet()) {
                String keyStr = key.toString();
                String value = props.getProperty(keyStr);
                propertyMap.put(keyStr, value);
            }
        }
    
        //static method for accessing context properties
        public static Object getProperty(String name) {
            return propertyMap.get(name);
        }
    }
    复制代码

    在配置文件中,用上面的类,代替PropertyPlaceholderConfigurer

      <bean id="propertyConfigurer" class="com.gyoung.mybatis.util.PropertyPlaceholder">
            <property name="location">
                <value>classpath:config.properties</value>
            </property>
        </bean>

    这样在代码中就可以直接用编程方式获取

     PropertyPlaceholder.getProperty("sql.name");
  • 相关阅读:
    【区间DP&&记忆化搜索】乘法游戏
    洛谷P1608路径统计
    2021省选游记
    涂色计划P4170
    01迷宫及路径记录(DFS&&BFS)
    [YBTOJ递推算法强化训练4]序列个数
    C++关于string 的优先队列以及重载运算符
    浅谈C++STL容器
    集合的划分
    图的表示
  • 原文地址:https://www.cnblogs.com/s648667069/p/6369601.html
Copyright © 2020-2023  润新知