• spring 集成的项目,Properties配置文件外移


     
     
    配置文件位于classpath下

      使用spring的org.springframework.beans.factory.config.PropertyPlaceholderConfigurer类加载Properties配置文件,通过源码可以知道,默认加载的是classpath下的文件,配置如下:

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

    如果有多个配置文件加载,则:

    <bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="locations">
       <list>
         <value>classpath:config/init.properties</value>
        <value>classpath:config/init.properties</value>
       </list>
      </property>
     </bean>

    这样spring就能够加载properties文件了。

    配置文件位于外部目录

      但是对于外部目录的配置文件,使用org.springframework.beans.factory.config.PropertyPlaceholderConfigurer也是可以加载的,不过要修改他的路径配置方式,如下:

    <bean id="placeholderConfig" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
      <property name="locations">
       <list>
         <value>file:${user.dir}/config/init.properties</value>
         <value>file:${user.dir}/config/init2.properties</value>
       </list>
      </property>
     </bean>

    这样就可以成功加载外部目录的配置文件了,${user.dir}是系统变量,指用户当前目录所在。

    代码中加载配置文件

      应该某些需求,配置文件得从java代码是加载,这里我就说一样代码中加载外部目录的配置文件的方式,加载classpath目录下的配置文件这里就不再多说了,相

    信网上有太多较好的简答。如下代码:

    private static final Properties sysConfig = new Properties();
     
        static {
            try {
                InputStream iStream = new FileInputStream(new File("config", "shellConfig.properties"));
                sysConfig.load(iStream);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        
        public static String getPropertyValue(String key){
            return sysConfig.getProperty(key);
        }

    原文: https://blog.csdn.net/chendeyou5/article/details/79449472

  • 相关阅读:
    nginx 处理跨域以及 OPTIONS预检请求
    EasyCVR智能边缘网关硬件全新升级,强劲性能从“芯”出发
    如何使用开源小工具goofys实现自动挂载对象存储桶到Linux?
    【操作步骤】如何自查判断视频平台是否私走流量?
    基于边缘AI计算的人员入侵检测CNN算法在实际场景中的应用
    MySQL 17 order by rand()
    MySQL45讲order by
    Http 状态码 及Rest 设计指南相
    微服务笔记
    Go相对路径问题
  • 原文地址:https://www.cnblogs.com/yrjns/p/12841017.html
Copyright © 2020-2023  润新知