前言
之所以想了解代碼生成器,是因爲mybatis的一個非常好用的輪子mybatisplus,還有spring boot這一些厲害的軟件都內置了代碼生成方面的內容,這些我挺感興趣的。
首先,可以先跑去Freemarker官網看看。相關的代碼和文檔說明還是十分清晰的。
不過,實踐出真知。照着官網的代碼Demo學習下。
啓程
工程截圖
pom.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<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>miv</groupId>
<artifactId>freemark.demo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
</dependencies>
</project>
Application.java
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;
import pojo.Product;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
public class Application {
public static void main(String[] args) throws Exception {
new Application().run();
}
public void run() throws Exception {
//配置模板目錄
Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
String fn = this.getClass().getClassLoader().getResource("templates").getPath();
System.out.println("模板目錄==>" + fn);
cfg.setDirectoryForTemplateLoading(new File(fn));
cfg.setDefaultEncoding("UTF-8");
//裝配數據
Map root = new HashMap();
root.put("user", "程序員");
Map latest = new HashMap();
root.put("latestProduct", latest);
latest.put("url", "https://www.apple.com");
latest.put("name", "Mac Pro 2018");
//指定模板
Template temp = cfg.getTemplate("test.ftl");
//渲染輸出
Writer out = new OutputStreamWriter(System.out);
temp.process(root, out);
}
}
模板文件
<html>
<head>
<title>Mac Pro新品發佈!</title>
</head>
<body>
<p>歡迎你,${user}</p>
<p>新品發佈:
<a href="${latestProduct.url}">${latestProduct.name}</a>!
</body>
</html>
運行效果
==>/D:/code/zip/mybatis-plus-samples/freemarkdemo/target/classes/templates
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<p>歡迎你,程序員</p>
<p>新品發佈:
<a href="https://www.apple.com">Mac Pro 2018</a>!
</body>
</html>