import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;
import org.springframework.util.StringUtils;
import java.util.HashMap;
import java.util.Map;
public class FreemarkerUtil {
final static Configuration cfg = new Configuration(Configuration.VERSION_2_3_28);
static {
cfg.setLocalizedLookup(false);
cfg.setDefaultEncoding("UTF_8");
cfg.setTemplateLoader(new SimpleStringTemplateLoader());
}
public static String render(String templateContent, Map<String, Object> param){
try {
if (!StringUtils.hasText(templateContent)){
return "";
}
Template template = cfg.getTemplate(templateContent);
String result = FreeMarkerTemplateUtils.processTemplateIntoString(template, param);
return result;
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String urlFormat = "jdbc:postgresql://${host}:${port}/${dbName}?currentSchema=<#if schemaName??>${schemaName}<#else>public</#if>&useSSL=false&stringtype=unspecified";
Map<String, Object> param=new HashMap<String, Object>(){{
put("host","localhost");
put("port","7300");
put("dbName","dbtest");
put("schemaName","test");
}};
String connectStr = FreemarkerUtil.render(urlFormat, param);
System.out.println(connectStr);
//jdbc:postgresql://localhost:7300/dbtest?currentSchema=test&useSSL=false&stringtype=unspecified
}
}
在pom.xml中引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
<version>2.1.4.RELEASE</version>
</dependency>