前言
之所以想了解代码生成器,是因为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>