zoukankan      html  css  js  c++  java
  • 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);
        }

     希望对大家有所帮助!

  • 相关阅读:
    .net core + mvc 手撸一个代码生成器
    如何使用VS Code编写Spring Boot (第二弹)
    第五章 .net core该怎么玩
    第四章 .net core做一个简单的登录
    第三章 搭建一个通用的权限管理系统
    第二章 在Linux上部署.net core
    将博客搬至CSDN
    Entity Framework6 with Oracle(可实现code first)
    利用windbg查找dictionary导致IIS占CPU100%案例分析(一)
    VS快捷键以及Reshaper快捷键
  • 原文地址:https://www.cnblogs.com/natgeo/p/2762328.html
Copyright © 2011-2022 走看看