code-generator for ftl template

"code-generator of ftl template"

1. Maven coordinates

<dependency>
    <groupId>org.freemarker</groupId>
    <artifactId>freemarker</artifactId>
    <version>2.3.31</version> <!-- 此处版本号可能会随着时间而变化,请确保使用最新稳定版 -->
</dependency>
 <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
 </dependency>

2. Create ftl template

{In the resource directory, create a templates folder and store templates in it}

Three, Java entity class generation case

entity_template.ftl template content

import lombok.Data;

@Data
public class ${className} {
<#list properties as property>
    private ${property.type} ${property.name};
</#list>
}

The generator code is as follows

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.IOException;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class CodeGenerator {

    public static void main(String[] args) throws IOException, TemplateException {
        // 准备数据模型
        Map<String, Object> dataModel = new HashMap<>();
        dataModel.put("className", "Person");

        List<Property> properties = new ArrayList<>();
        properties.add(new Property("String", "name"));
        properties.add(new Property("int", "age"));
        properties.add(new Property("String", "email"));

        dataModel.put("properties", properties);

        // 加载FTL模板
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
        configuration.setClassLoaderForTemplateLoading(CodeGenerator.class.getClassLoader(), "templates");
        Template template = configuration.getTemplate("entity_template.ftl");

        // 将数据模型和FTL模板合并生成Java实体类代码
        StringWriter stringWriter = new StringWriter();
        template.process(dataModel, stringWriter);

        // 输出生成的Java实体类代码
        System.out.println(stringWriter.toString());
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Property {
        private String type;
        private String name;
    }

}

Four, the effect is as follows

insert image description here

ftl templates that can be highly customized to generate code…. Such as html, vue, Java, etc. {Look at the ftl syntax}

Guess you like

Origin blog.csdn.net/weixin_52236586/article/details/131856657