FreeMarker的maven引用及application配置见第一篇教程
SpringBoot+FreeMarker 学习(一)初识FreeMarker
在resources/templates中创建模板文件file.ftl
package ${classPath};
public class ${className} {
public static void main(String[] args) {
System.out.println("${helloWorld}");
}
}
创建FileController,写生成文件接口
@RestController
@RequestMapping(value = "/file")
public class FileController {
@Resource
private Configuration configuration;
@GetMapping("/export")
public String export() {
try {
Map<String, Object> export = new HashMap<>();
export.put("classPath", "com.by.test");
export.put("className", "ExportTest");
export.put("helloWorld", "Hello World!");
Template template = configuration.getTemplate("file.ftl");
File file = new File("ExportTest.java");
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8));
template.process(export, out);
out.close();
} catch (IOException | TemplateException e) {
e.printStackTrace();
return "生成失败";
}
return "生成成功";
}
}
启动项目,访问 http://127.0.0.1:8080/file/export
页面显示
则在项目根目录中生成了一个名称为ExportTest.java的java文件,内容如下
package com.by.test;
public class ExportTest {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
生成文件成功。