有时候在写配置文件时,可能需要我们进行动态的传参,可以采用下面的方法:
配置文件,{0}是传的第一参数,{1}是传的第二个参数
jdbc.url=jdbc:mysql://{0}:3306/{1}
// 这里谢了加载配置文件的两种方法
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import org.junit.Test;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.Properties;
/**
* @Author: zxl
* @Date: 2019/1/11 19:39
* @Version 1.0
*/
public class Demo02 {
static Properties prop = new Properties();
static Config load ;
static {
load = ConfigFactory.load("a.properties"); // 第一种加载配置文件的方法, 如果配置文件是application.properties ,就直接ConfigFactory.load() 会默认加载,需要导入依赖
}
//
public Demo2(){
try { 第二种加载配置文件的方式
// 加载配置文件 ,配置文件名为a.properties,放在resourceManager, 使用类加载器
prop.load(this.getClass().getClassLoader().getResourceAsStream("a.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void test01(){
String url = MessageFormat.format(prop.getProperty("jdbc.url"),"localhost", "MyTest");
System.out.println(url);
}
@Test
public void test02(){
String url = MessageFormat.format(load.getString("jdbc.url"),"192.168.136.150", "MyTest1");
System.out.println(url);
}
}