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

猜你喜欢

转载自www.cnblogs.com/zhaijing/p/9706941.html