import org.apache.commons.lang.text.StrSubstitutor;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
public class Test {
public static void main(String[] args) {
//方法一
String url = "jdbc:mysql://{ip}:{port}/{tenantCode}?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai";
String context = url.replace("{ip}", "127.0.0.1").replace("{port}", "3306").replace("{tenantCode}", "test001");
System.out.println(context);
//方法二
String url1 = "jdbc:mysql://%s:%s/%s?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai";
String context1 = String.format(url1, "127.0.0.1", "3306", "test001");
System.out.println(context1);
//方法三
String url2 = "jdbc:mysql://{0}:{1}/{2}?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai";
String context2 = MessageFormat.format(url2, "127.0.0.1", "3306", "test001");
System.out.println(context2);
//方法四-需要引用commons-lang3或commons-text包
Map map = new HashMap<>();
map.put("ip", "127.0.0.1");
map.put("port", "3306");
map.put("tenantCode", "test001");
StrSubstitutor strSubstitutor = new StrSubstitutor(map);
String url3 = "jdbc:mysql://${ip}:${port}/${tenantCode}?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai";
String context3 = strSubstitutor.replace(url3);
System.out.println(context3);
}
}
结果
jdbc:mysql://127.0.0.1:3306/test001?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai
jdbc:mysql://127.0.0.1:3306/test001?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai
jdbc:mysql://127.0.0.1:3306/test001?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai
jdbc:mysql://127.0.0.1:3306/test001?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&serverTimezone=Asia/Shanghai