FreeMarker极简Demo

什么是 FreeMarker?

FreeMarker 是一款 模板引擎: 即一种基于模板和要改变的数据, 并用来生成输出文本(HTML网页,电子邮件,配置文件,源代码等)的通用工具。 它不是面向最终用户的,而是一个Java类库,是一款程序员可以嵌入他们所开发产品的组件。

下面是一个超简单的Demo:

整体结构:


pom.xml中添加依赖:

    <dependencies>
        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.20</version>
        </dependency>
    </dependencies>

创建一个模板 1.ftl 

public class ${className} {

}

创建类:

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

public class FreeMarkerDemo {
    public static void CodeMaker(String className) {
        Configuration conf = new Configuration();
        String dir = "E:\\jProjects\\demo\\freemarkerdemo\\src\\main\\resources\\templates\\";
        try {
            conf.setDirectoryForTemplateLoading(new File(dir));

            Template template = conf.getTemplate("1.ftl");

            Writer out =new FileWriter(new File(dir + className + ".java"));

            Map<String,Object> dataModel = new HashMap<String,Object>();
            dataModel.put("className", className);
            template.process(dataModel, out);

            out.flush();
            out.close();

        } catch (Exception e) {

        }
    }
}

调用的地方:

import java.util.ArrayList;
import java.util.List;

public class Applaction {
    public static void main(String[] args) throws Exception {
        List<String> list=new ArrayList<String>();
        list.add("TestClass1");
        list.add("TestClass2");
        for (String s : list) {
            FreeMarkerDemo.CodeMaker(s);
        }
    }
}

执行一下程序:


两个文件就创建好了


猜你喜欢

转载自blog.csdn.net/weixin_42018258/article/details/79993048