• java如何加载不同环境的properties配置文件?


    写一个加载配置文件的类:

    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.util.Properties;
    
    public class Config{
        private static final Config_path="env.properties";
        private Properties propertyFile=new Properties();
        public static final String server="server";
    
        /**
        *构造类时加载配置文件
        **/
        public Config(){
          try{
              String path=this.getClass.getClassLoader().getResource(this.Config_path).getPath();
              InputStream in=new FileInputStream(path);
              propertyFile.load(in);
          }catch(Exception e){
              e.printStackTrace;
          }
        }
        
        public String getServer(){
            return propertyFile.getProperty(server);
        }
    
    }

    env.properties的内容

    server=http://www.baidu.com

    尝试把配置文件路经的值打印出来如下: 工程目录/target/classes/env.properties

    可以看到加载的是编译之后的配置文件

    如何使用配置类?

    Config config=new Config();
    String server=config.getServer();

    如果环境中用到不同的配置文件,可以在pom.xml中配置不同的profile,使用mvn 编译的时候使用-P选项指定相应的profile文件,就会把指定profile下面的配置文件进行编译

    <profiles>
            <profile>
                <id>preonline</id>
                <build>
                    <resources>
                        <resource>
                            <directory>src/test/profiles/preonline</directory>
                        </resource>
                    </resources>
                </build>
            </profile>
    
            <profile>
            <id>prod</id>
            <activation>
                <activeByDefault>false</activeByDefault>
            </activation>
            <build>
                <resources>
                    <resource>
                        <directory>src/test/profiles/prod</directory>
                    </resource>
                </resources>
            </build>
            </profile>
    
            <profile>
            <id>test</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <build>
                <resources>
                    <resource>
                        <directory>src/test/profiles/test</directory>
                    </resource>
                </resources>
            </build>
            </profile>
        </profiles>

    //使用-P选项指定id=test的这个profile,编译完之后可以看到会把src/test/profiles/test下面的env.properties文件编译到target/classes文件夹下面

    mvn clean compile -Ptest

  • 相关阅读:
    [daily][netcat] 在UNIX socket上使用netcat
    [emacs] emacs设置python code的indent
    [dev][python] 从python2进阶到python3你都需要了解什么
    [strongswan][autoconf][automake][cento] 在CentOS上编译strongswan git源码时遇到的autoconf问题
    [strongswan] strongswan是如何实现与xfrm之间的trap机制的
    对不可描述的软件安装sfbo插件
    [daily] 如何用emacs+xcscope阅读内核源码
    [daily] cscope
    [dev][ipsec] 什么是xfrm
    [dev][ipsec] netlink是什么
  • 原文地址:https://www.cnblogs.com/zhaijing/p/9706941.html
Copyright © 2020-2023  润新知