首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

FreeMarker 實戰教學:模板引擎自動生成 Java 實體類代碼完整範例

     編輯:Java 相關知識

核心公式

Template + Data Model = Output

目標輸出:Java 實體類


package com.cs.qdog.swift.objects;
public class F32B {
    private Double amount;
    private String currency;
    public Double getAmount() { return amount; }
    public void setAmount(Double amount) { this.amount = amount; }
    public String getCurrency() { return currency; }
    public void setCurrency(String currency) { this.currency = currency; }
}

資料模型(樹狀結構)

(root)
|
+- class = "F32B"
|
+- properties
   |
   +- currency : { name="currency", type="String" }
   +- amount   : { name="amount",   type="Double" }

FreeMarker 模板


package com.cs.qdog.swift.objects;
public class ${class} {
<#list properties as prop>
    private ${prop.type} ${prop.name};

<#list properties as prop>
    public ${prop.type} get${prop.name?cap_first}() {
        return ${prop.name};
    }
    public void set${prop.name?cap_first}(${prop.type} ${prop.name}) {
        this.${prop.name} = ${prop.name};
    }

}

關鍵指令:
<#list properties as prop> 遍歷集合
${prop.name?cap_first} 首字母大寫(getAmount/setAmount)

Java 驅動程式


public class GenObjects {
    public static void main(String[] args) throws IOException, TemplateException {
        // 1. 配置
        Configuration cfg = new Configuration();
        cfg.setDirectoryForTemplateLoading(new File("D:/.../templates"));
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        // 2. 取得模板
        Template temp = cfg.getTemplate("SwiftFieldClass.ftl");
        // 3. 建構資料模型
        Map root = new HashMap();
        root.put("class", "F32B");
        Collection properties = new HashSet();
        root.put("properties", properties);
        Map currency = new HashMap(); currency.put("name","currency"); currency.put("type","String"); properties.add(currency);
        Map amount = new HashMap(); amount.put("name","amount"); amount.put("type","Double"); properties.add(amount);
        // 4. 合併輸出
        Writer out = new OutputStreamWriter(System.out);
        temp.process(root, out);
        out.flush();
    }
}

擴展應用場景

  • 批量生成 Entity/DAO/Service/Controller 全層代碼
  • 根據資料庫 Schema 反向生成代碼
  • 配置檔、SQL、文檔自動生成

FreeMarker 以「模板+資料」極簡模型,賦予代碼生成極大靈活性與可維護性。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved