freemaker这个jar包可以更加有提前编辑好的模板生成Java代码,做到“不写重复代码”。
实现的步骤如下:
第一步:springboot的pom.xml文件加入依赖包
<dependency><groupId>org.freemarkergroupId><artifactId>freemarkerartifactId><version>2.3.23version>dependency>
第二步&#xff1a;编写模板
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}&#61;${Id};
}public String get${userName}(){
return ${userName};
}public void set${userName}(String ${userName}){
this.${userName}&#61;${userName};}public String get${password}(){
return ${password};
}public void set${password}(String ${password}){
this.${password}&#61;${password};
}}
第三步&#xff1a;编写生成代码的类
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 &#61; "src/main/java/com/chen/www/chendemo/CodeGenerator";private static final String CLASS_PATH &#61; "src/main/java/com/chen/www/chendemo/CodeGenerator";public static void main(String[] args) {Configuration configuration &#61; new Configuration();Writer out &#61; null;try {configuration.setDirectoryForTemplateLoading(new File(TEMPLATE_PATH));Map<String, Object> dataMap &#61; 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");Template template &#61; configuration.getTemplate("test.ftl");File docFile &#61; new File(CLASS_PATH &#43; "\\" &#43; "User.java");out &#61; new BufferedWriter(new OutputStreamWriter(new FileOutputStream(docFile)));template.process(dataMap, out);System.out.println("文件创建成功 !");} catch (Exception e) {e.printStackTrace();} finally {try {if (null !&#61; out) {out.flush();}} catch (Exception e2) {e2.printStackTrace();}}}}
文件目录如下&#xff1a;