Freemarker动态替换JDBC的URL中的占位符,可以给默认值



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 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&useSSL=false&stringtype=unspecified";
        Map param=new HashMap(){{
            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中引入依赖


            org.springframework.boot
            spring-boot-starter-freemarker
            2.1.4.RELEASE
        

你可能感兴趣的:(java,Freemarker)