freemarker簡單案例
阿新 • • 發佈:2018-12-10
- 一、環境說明:win10專業版、jdk1.8.0_171、eclipse4.7.3a、Junit5
- 二、步驟說明:
- 1.建立一個簡單的maven工程freemarker
- 2.引入pom依賴,pom檔案具體如下:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.szcatic</groupId> <artifactId>freemarker</artifactId> <version>0.0.1-SNAPSHOT</version> <dependencies> <!-- junit5執行所需jar包 --> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-engine</artifactId> <version>5.2.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.platform</groupId> <artifactId>junit-platform-runner</artifactId> <version>1.2.0</version> <scope>test</scope> </dependency> <dependency> <groupId>org.freemarker</groupId> <artifactId>freemarker</artifactId> <version>2.3.28</version> </dependency> </dependencies> </project>
- 3.編寫工具類
package com.szcatic.util; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.HashMap; import java.util.Map; import com.szcatic.entity.Model; import freemarker.template.Configuration; import freemarker.template.Template; import freemarker.template.TemplateException; import freemarker.template.TemplateExceptionHandler; /** * 程式碼生成器工具類 * @author zsx * @version 2018-09-17 * */ public class CodeGeneratorUtils { /** * * @param templatePath 模板路徑 * @param templateName 模板名稱 * @param filePath 生成檔案的路徑 * @param fileName 生成檔案的名稱 * @param model 生成模型 */ public static void genCode(String templatePath, String templateName, String filePath, String fileName, Map<String, Object> model) { OutputStream os = null; try { Configuration cfg = new Configuration(Configuration.VERSION_2_3_22); cfg.setDirectoryForTemplateLoading(new File(templatePath)); cfg.setDefaultEncoding("UTF-8"); cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER); Template temp = cfg.getTemplate(templateName); File dir = new File(filePath); if(!dir.exists()) { dir.mkdirs(); } os = new FileOutputStream(new File(dir, fileName)); Writer out = new OutputStreamWriter(os); temp.process(model, out); System.out.println("gen code success!"); os.flush(); } catch (IOException e) { e.printStackTrace(); } catch (TemplateException e) { e.printStackTrace(); }finally { if (os != null) { try { os.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 獲取模型資料 * @param model * @return */ public static Map<String, Object> getModel(Model model) { Map<String, Object> map = new HashMap<String, Object>(); map.put("model", model); return map; } }
- 4.建立模型實體類
package com.szcatic.entity; import java.io.Serializable; import java.util.List; /** * 模板實體類 * * @author zsx * @version 2018-09-17 * */ public class Model implements Serializable { private static final long serialVersionUID = 1L; private String packageName; // 包名 private String author; // 作者 private String version; // 版本號 private String className; // 類名 private String classDescription; // 類描述 private List<ClassAttribute> classAttributes; // 類屬性列表 public Model() { super(); } public Model(String packageName, String author, String version, String className, String classDescription, List<ClassAttribute> classAttributes) { super(); this.packageName = packageName; this.author = author; this.version = version; this.className = className; this.classDescription = classDescription; this.classAttributes = classAttributes; } public String getPackageName() { return packageName; } public void setPackageName(String packageName) { this.packageName = packageName; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getClassDescription() { return classDescription; } public void setClassDescription(String classDescription) { this.classDescription = classDescription; } public List<ClassAttribute> getClassAttributes() { return classAttributes; } public void setClassAttributes(List<ClassAttribute> classAttributes) { this.classAttributes = classAttributes; } @Override public String toString() { return "Model [packageName=" + packageName + ", author=" + author + ", version=" + version + ", className=" + className + ", classDescription=" + classDescription + ", classAttributes=" + classAttributes + "]"; } }
- 5.建立類屬性實體類
package com.szcatic.entity; import java.io.Serializable; /** * 類屬性實體類 * * @author zsx * @version 2018-09-17 * */ public class ClassAttribute implements Serializable { private static final long serialVersionUID = 1L; private String attributeName; // 屬性名 private String attributeType; // 屬性型別 public ClassAttribute() { super(); } public ClassAttribute(String attributeName, String attributeType) { super(); this.attributeName = attributeName; this.attributeType = attributeType; } public String getAttributeName() { return attributeName; } public void setAttributeName(String attributeName) { this.attributeName = attributeName; } public String getAttributeType() { return attributeType; } public void setAttributeType(String attributeType) { this.attributeType = attributeType; } @Override public String toString() { return "ClassAttribute [attributeName=" + attributeName + ", attributeType=" + attributeType + "]"; } }
- 6.編寫模板檔案,檔名為model.ftl
package ${model.packageName}; import java.io.Serializable; /** * ${model.classDescription} * @author ${model.author} * @version ${model.version} */ public class ${model.className} implements Serializable { private static final long serialVersionUID = 1L; <#list model.classAttributes as classAttribute> private ${classAttribute.attributeType} ${classAttribute.attributeName}; </#list> <#list model.classAttributes as classAttribute> public void set${classAttribute.attributeName?cap_first}(${classAttribute.attributeType} ${classAttribute.attributeName}){ this.${classAttribute.attributeName} = ${classAttribute.attributeName}; } public ${classAttribute.attributeType} get${classAttribute.attributeName?cap_first}(){ return this.${classAttribute.attributeName}; } </#list> }
- 7.編寫測試類CodeGeneratorUtilsTest
package com.szcatic.test; import java.util.ArrayList; import java.util.List; import java.util.Map; import org.junit.jupiter.api.Test; import com.szcatic.entity.ClassAttribute; import com.szcatic.entity.Model; import com.szcatic.util.CodeGeneratorUtils; public class CodeGeneratorUtilsTest { @Test void testGenCode() { String templatePath = ClassLoader.getSystemClassLoader().getResource("").getPath(); String templateName = "model.ftl"; String filePath = "src/main/java/com/szcatic/entity"; String fileName = "User.java"; List<ClassAttribute> classAttributes = new ArrayList<>(); ClassAttribute classAttribute = new ClassAttribute("id", "Long"); classAttributes.add(classAttribute); ClassAttribute classAttribute2 = new ClassAttribute("name", "String"); classAttributes.add(classAttribute2); ClassAttribute classAttribute3 = new ClassAttribute("age", "Integer"); classAttributes.add(classAttribute3); Model model = new Model("com.szcatic.entity", "zsx", "2018-09-17", "User", "使用者實體類", classAttributes); Map<String, Object> map = CodeGeneratorUtils.getModel(model); CodeGeneratorUtils.genCode(templatePath, templateName, filePath, fileName, map); } }
執行測試方法,控制檯輸出如下,表示生成檔案成功
gen code success!
- 8.最後重新整理專案,結構如下: