java如何加載不同環境的properties配置文件?
阿新 • • 發佈:2018-09-26
his import nts tor tac mpi new private XML
寫一個加載配置文件的類:
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
java如何加載不同環境的properties配置文件?