<dependency>
<groupId>org.freemarkergroupId>
<artifactId>freemarkerartifactId>
<version>2.3.31version>
dependency>
<dependency>
<groupId>org.projectlombokgroupId>
<artifactId>lombokartifactId>
<optional>trueoptional>
dependency>
{resource目录下,创建templates文件夹、里面存放模板}
entity_template.ftl 模板内容
import lombok.Data;
@Data
public class ${className} {
<#list properties as property>
private ${property.type} ${property.name};
#list>
}
生成器代码如下
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 dataModel = new HashMap<>();
dataModel.put("className", "Person");
List 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;
}
}
ftl模板,可以高度自定义生成代码…。如html、vue、Java等。{看一下ftl语法即可}