freemarker代码生成
利用模板来生成代码
添加 freemarker 依赖包
<dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.23</version> </dependency>
创建一个代码模版
以动态创建实体类为例,编写一个实体类的模板entity.java.ftl
,其中${}
里面定义的是动态变量。
package ${package}; import java.io.Serializable; /** * <p> * ${tableComment} * </p> * * @author ${author} * @since ${date} */ public class ${entityClass} implements Serializable { private static final long serialVersionUID = 1L; <#--属性遍历--> <#list columns as pro> /** * ${pro.comment} */ private ${pro.propertyType} ${pro.propertyName}; </#list> <#--属性get||set方法--> <#list columns as pro> public ${pro.propertyType} get${pro.propertyName?cap_first}() { return this.${pro.propertyName}; } public ${entityClass} set${pro.propertyName?cap_first}(${pro.propertyType} ${pro.propertyName}) { this.${pro.propertyName} = ${pro.propertyName}; return this; } </#list> }
生成目标代码
基于freemarker
编写一个测试类!
public class CodeGeneratorDemo { public static void main(String[] args) throws IOException, TemplateException { Map<String, Object> objectMap = new HashMap<>(); //定义包路径 objectMap.put("package", "com.xc.xcspringboot.test"); //定义实体类 objectMap.put("entityClass", "Student"); //定义实体类属性 List<Map<String, Object>> columns = new ArrayList<>(); //姓名字段 Map<String, Object> column1 = new HashMap<>(); column1.put("propertyType", "String"); column1.put("propertyName", "name"); column1.put("comment", "姓名"); columns.add(column1); //年龄字段 Map<String, Object> column2 = new HashMap<>(); column2.put("propertyType", "Integer"); column2.put("propertyName", "age"); column2.put("comment", "年龄"); columns.add(column2); //定义类的属性 objectMap.put("columns", columns); //定义作者 objectMap.put("author", "张三"); //定义创建时间 objectMap.put("date", new SimpleDateFormat("yyyy-MM-dd").format(new Date())); //定义类描述 objectMap.put("tableComment", "学生信息"); //生产目标代码 Configuration configuration = new Configuration(Configuration.VERSION_2_3_23); configuration.setDefaultEncoding(Charset.forName("UTF-8").name()); configuration.setClassForTemplateLoading(CodeGeneratorDemo.class, "/"); Template template = configuration.getTemplate("/templates/entity.java.ftl"); FileOutputStream fileOutputStream = new FileOutputStream( new File("D:\\project\\intellij-git\\xc-springboot\\src\\main\\java\\com\\xc\\xcspringboot\\test/Student.java")); template.process(objectMap, new OutputStreamWriter(fileOutputStream, Charset.forName("UTF-8").name())); fileOutputStream.close(); System.out.println("文件创建成功"); } }
官方文档: http://freemarker.foofun.cn/pgui_quickstart_createconfiguration.html
参考文章: https://mp.weixin.qq.com/s/uXR6gHYyZ1tlKtdQPyDn9w