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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM