zoukankan      html  css  js  c++  java
  • Spring用代码来读取properties文件

    我们都知道,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");
    //或者
    @Value("#{'${sql.name}'.split(',')}")
    private List<String> nameList;

    如果是多个配置文件,配置locations属性

    <bean id="propertyConfigurer"
              class="com.gyoung.mybatis.util.PropertyPlaceholder">
            <property name="ignoreResourceNotFound" value="true"/>
            <property name="locations">
                <list>
                    <value>file:./jdbc.properties</value>
                    <value>file:./module.config.properties</value>
                    <value>classpath:jdbc.properties</value>
                    <value>classpath*:*.config.properties</value>
                </list>
            </property>
        </bean>

    转自:https://www.cnblogs.com/Gyoung/p/5507063.html

  • 相关阅读:
    java 备忘
    C++ 命名规范 (转)
    代码格式规范
    using namespace 由来
    结构体数组 初始化(转)
    Java Servlet系列之Servlet生命周期
    进程,内存,管理 ps,pstree,top,free,vmstat,iftop,lsof,查看网速
    网络基础知识-
    进程作业管理2-kill,前后台作业,并行执行
    计划任务cron,date,时间同步ntp,chrony
  • 原文地址:https://www.cnblogs.com/penghq/p/13614778.html
Copyright © 2011-2022 走看看