FreeMarker之根据模板生成Java代码

时间:2023-03-08 22:04:59

FreeMarker根据模板生成Java代码,光这句话,大家想必也知道它的应用了,比如流行的DRY原则,该原则的意思,可简单概述为"不要写重复的代码"。

比如Java中三层架构,数据访问层,业务逻辑层,表现层,光这三层就出现重复性的增删改查及其相关的界面代码。

如何不写重复的增删改查相关的代码,可以参考我的MP实战系列文章和MyBatis的逆向工程(针对Java相关框架):

mybatis逆向工程之maven工程

MP实战系列(六)之代码生成器讲解

其中MP实战系列(六)之代码生成器讲解 用的是volocity模板引擎。原理与FreeMarker本质上是一致的,这个本质一致,你可以理解为都是基于已有的模板进行代码生成。

下面进入简单示例讲解:

一、导入maven依赖

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.test</groupId>
<artifactId>freemarket</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging> <dependencies>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.23</version>
</dependency> </dependencies>
<build> <plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin> <!-- <plugin>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
</configuration>
</plugin> --> </plugins>
<finalName>${project.artifactId}</finalName>
</build>
</project>

二、新建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; 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<String, Object> dataMap = new HashMap<String, Object>();
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类

小结:该示例非常简单,freemarker的强大不足以在此体现,不过该示例对于初学者或者准备研究freemarker的开发者有一定的启示意义。

比如:遵守"DRY原则",对于开发效率的提高,帮助非常大。