一、导入maven依赖
点击(此处)折叠或打开
-
<dependency>
-
<groupId>org.freemarker</groupId>
-
<artifactId>freemarker</artifactId>
-
<version>2.3.23</version>
- </dependency>
二、新建com.freemarker.hello.templates包,并在该包下编写模板文件test.ftl
点击(此处)折叠或打开
-
package ${classPath};
-
public class ${className} {
-
-
private Integer ${Id};
-
-
private String ${userName};
-
-
private String ${password};
-
-
-
public Integer get${Id}(){
-
-
return ${Id};
-
-
}
-
-
-
public void set${Id}(Integer ${Id}){
-
-
this.${Id}=${Id};
-
-
}
-
-
-
public String get${userName}(){
-
-
return ${userName};
-
-
}
-
-
public void set${userName}(String ${userName}){
-
-
this.${userName}=${userName};
-
-
}
-
-
-
public String get${password}(){
-
-
return ${password};
-
-
}
-
-
-
public void set${password}(String ${password}){
-
-
this.${password}=${password};
-
-
}
-
- }
三、编写运行生成对应Java代码类
点击(此处)折叠或打开
-
package com.freemark.hello;
-
-
-
-
import java.io.BufferedWriter;
-
-
import java.io.File;
-
-
import java.io.FileOutputStream;
-
-
import java.io.OutputStreamWriter;
-
-
import java.io.Writer;
-
-
import java.util.HashMap;
-
-
import java.util.Map;
-
-
-
-
import freemarker.template.Configuration;
-
-
import freemarker.template.Template;
-
-
-
-
//java项目www fhadmin org
-
-
public class FreemarkerDemo {
-
-
-
-
private static final String TEMPLATE_PATH = "src/main/java/com/freemark/hello/templates";
-
-
private static final String CLASS_PATH = "src/main/java/com/freemark/hello";
-
-
-
public static void main(String[] args) {
-
-
// step1 创建freeMarker配置实例
-
-
Configuration configuration = new Configuration();
-
-
Writer out = null;
-
-
try {
-
-
// step2 获取模版路径
-
-
configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));
-
-
// step3 创建数据模型
-
-
Map dataMap = new HashMap();
-
-
dataMap.put("classPath", "com.freemark.hello");
-
-
dataMap.put("className", "User");
-
-
dataMap.put("Id", "Id");
-
-
dataMap.put("userName", "userName");
-
-
dataMap.put("password","password");
-
-
// step4 加载模版文件
-
-
Template template = configuration.getTemplate("test.ftl");
-
-
// step5 生成数据
-
-
File docFile = new File(CLASS_PATH + "\\" + "User.java");
-
-
out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));
-
-
// step6 输出文件
-
-
template.process(dataMap, out);
-
-
System.out.println("^^^^^^^^^^^^^^^^^^^^^^^^User.java 文件创建成功 !");
-
-
} catch (Exception e) {
-
-
e.printStackTrace();
-
-
} finally {
-
-
try {
-
-
if (null != out) {
-
-
out.flush();
-
-
}
-
-
} catch (Exception e2) {
-
-
e2.printStackTrace();
-
-
}
-
-
}
-
-
}
-
-
- }
四、步骤三成功,刷新(refresh)项目即可,看到com.freemark.hello有一个User类。