前言
现实开发中会遇到很多重复代码的情况,比如说一些实体类,配置文件,一些mapper等等。这种重复而无意义的代码无疑增加了我们开发工时,所以在这里简单的记录一下使用freemarker的步骤
提示:以下是本篇文章正文内容,下面案例可供参考
一、freemarker简单理解
freemarker是apache下的一个模板生成工具详情,他可以对一些通用模板中的字符进行替换,提高我们的开发效率。
二、使用步骤
1.项目中引入freemarker
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.30</version>
</dependency>
2.加载freemarker配置
Configuration configurationConfiguration configuration = new Configuration(Configuration.getVersion());
注:Configuration 是freemarker包下的配置类
3.设置模板路径
path = this.getClass().getClassLoader().getResource("").getPath() + "template"; // 加载模板所在的位置
configuration.setDirectoryForTemplateLoading(new File(path)); // 设置模板路径
4.获取模板
Template template = configuration.getTemplate(templateName);
5.设置文件生成路径,并且根据模板生成代码
FileOutputStream fout = new FileOutputStream(new File(outputPath));
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fout);
template.process(data, outputStreamWriter);
6.配置模板
在相应的路径下配置模板,如下:
注:模板是以ftl文件
7.freemarker模板配置介绍(这里只介绍刚需配置)
任何一种编程语言的基础语法其实都是类似的,无非就是一些判断,循环,等等。freemarker模板配置无非也是如此
1.常量替换
${param},第五步中生成代码的时候,会根据具体的参数名称替换成具体的内容;例如${name}, 当我们传递的数据参数是
ImmutableMap.of("name", "hello"); 那么${name}会被替换成hello。传递具体的对象也是可以的。例如以下模板
姓名:${testDO.name}
年龄:${testDO.age}
性别:${testDO.sex}
传递如下类中的对象
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class TestDO {
private String name;
private int age;
private String sex;
}
调用方法如下:
public static void main(String[] args) {
FreeMarkerCodeUtil freeMarkerCodeUtil = new FreeMarkerCodeUtil();
TestDO testDO = TestDO.builder().age(10).name("test").sex("男").build();
ImmutableMap.of("name", "hello");
Map<String, Object> data = Maps.newHashMap();
data.put("testDO", testDO);
freeMarkerCodeUtil.generator("hello.ftl", "C:\\Users\\86187\\Desktop\\测试\\A.txt",data);
}
生成结果如下:
姓名:test
年龄:10
性别:男
2.条件判断
<#if name == "freemarker">
#{name}我真的要减肥了!!!
</#if>
3.循环
<#list lists as item>
${item.name}
<#list>
具体使用方法如第一步
FreeMarkerCodeUtil 代码如下:
import freemarker.template.Configuration;
import freemarker.template.Template;
import java.io.*;
public class FreeMarkerCodeUtil {
private String path;
private Configuration configuration;
private void init() throws IOException {
configuration = new Configuration(Configuration.getVersion());
path = this.getClass().getClassLoader().getResource("").getPath() + "template";
configuration.setDirectoryForTemplateLoading(new File(path));
}
public void generator(String templateName, String outputPath, Object data) {
try {
init();
Template template = configuration.getTemplate(templateName);
FileOutputStream fout = new FileOutputStream(new File(outputPath));
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fout);
template.process(data, outputStreamWriter);
} catch (Exception e) {
e.printStackTrace();
}
}
}
总结
通过上面的简单介绍我想大家对freemarker有了一个初步的认识,通过freemarker我们可以根据模板生成我们想要的代码