一、Maven导入Freemarker的jar包:
在 https://mvnrepository.com/ 中搜索 freemarker。
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
二、代码如下:
/** FreeMarker模板所在路径 */
private static final String TEMPLATE_PATH = "src\\main\\resources\\ftl";
/** 通过FreeMarker生成的文件存放路径 */
private static final String CLASS_PATH = "src\\main\\java\\com\\test\\freemarker";
@Test
void test() {
// 1、创建freeMarker配置实例
Configuration configuration = new Configuration(Configuration.VERSION_2_3_30);
FileWriter fw = null;
try {
// 2、 获取模版路径
configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));
// 3、 创建数据模型
Map<String, Object> dataMap = new HashMap<>();
dataMap.put("model", "User");
dataMap.put("entity", "UserEO");
// 4、 加载模版文件
Template template = configuration.getTemplate("BaseController.ftl");
// 5、生成数据
fw = new FileWriter(CLASS_PATH + "\\" + "User" + "Controller.java");
// 6、输出文件
template.process(dataMap, fw);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.flush();
} catch (IOException e) {
e.printStackTrace();
}
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
三、模板文件BaseController.ftl内容:
public class ${model}Controller {
public Object getModel() {
return "${model}";
}
public Object getEntity() {
return new ${entity}();
}
}