freemaker这个jar包可以更加有提前编辑好的模板生成Java代码,做到“不写重复代码”。
实现的步骤如下:
第一步:springboot的pom.xml文件加入依赖包
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency>
第二步:编写模板
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};
}
}
第三步:编写生成代码的类
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;
public class FreemarkerDemo {
private static final String TEMPLATE_PATH = "src/main/java/com/chen/www/chendemo/CodeGenerator";
private static final String CLASS_PATH = "src/main/java/com/chen/www/chendemo/CodeGenerator";
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<String, Object> dataMap = new HashMap<String, Object>();
dataMap.put("classPath", "com.chen.www.chendemo");
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("文件创建成功 !");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != out) {
out.flush();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
}
文件目录如下: