FreeMarker 介绍

入门

1)引入 Maven 依赖

        
        
            org.freemarker
            freemarker
            2.3.31
        

2.1 )定义测试所需类

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class ImageDetail {
    private long id;
    private int width;
    private int height;
    private String name;
    private String extension;
}

2.2)在 src/main/resources/templates 目录下,新建 example.ftl 文件,内容如下:

<#assign fromClassVar="${fromClassName?uncap_first}">

private ${toClassName} convert(${fromClassName} ${fromClassVar}) {
    return ${toClassName}.builder()

    <#list fields as field>
        .${field}(${fromClassVar}.get${field?cap_first}())
    

        .build();
}

3)新建测试类 FreeMarkerTest

public class FreeMarkerTest {
    public static void main(String[] args) throws IOException, TemplateException {
        Configuration conf = new Configuration();
        // 设置加载模板文件的目录
        conf.setDirectoryForTemplateLoading(new File("src/main/resources/templates"));
        // 设置模板检索数据模型的方式
        conf.setObjectWrapper(new DefaultObjectWrapper());
        // 创建、解析模板并缓存
        Template template = conf.getTemplate("example.ftl");
        // 准备数据
        Map root = new HashMap();
        Class imageDetailClass = ImageDetail.class;
        root.put("toClassName", imageDetailClass.getSimpleName());
        root.put("fromClassName", imageDetailClass.getSimpleName());

        List fields = Arrays.stream(imageDetailClass.getDeclaredFields())
            .map(Field::getName)
            .collect(Collectors.toList());
        root.put("fields", fields);

        // 将数据与模板合并
        printAndIgnoreBlankLine(template, root);
    }

    @SneakyThrows
    public static void printAndIgnoreBlankLine(Template template, Map root) {
        StringWriter stringWriter = new StringWriter();
        template.process(root, stringWriter);
        String lines[] = stringWriter.toString().split("\\r?\\n");
        for (String line : lines) {
            if (StringUtils.isNotBlank(line)) {
                System.out.println(line);
            }
        }
    }
}

StringUtils.isNotBlank() 是 https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 的工具类。

  1. 运行 FreeMarkerTest,输出如下:
private ImageDetail convert(ImageDetail imageDetail) {
    return ImageDetail.builder()
        .id(imageDetail.getId())
        .width(imageDetail.getWidth())
        .height(imageDetail.getHeight())
        .name(imageDetail.getName())
        .extension(imageDetail.getExtension())
        .build();
}

参考

  • FreeMarker开发-入门
  • 什么是 FreeMarker? - 官方中文网
  • Freemarker 教程(一)-模板开发手册

你可能感兴趣的:(FreeMarker 介绍)