一 FreeMarker简介

Apache FreeMarker是一个Java模板引擎库,官网:http://freemarker.incubator.apache.org/。

Apache FreeMarker is a template engine: a Java library to generate
text output (HTML web pages, e-mails, configuration files, source
code, etc.) based on templates and changing data. Templates are
written in the FreeMarker Template Language (FTL), which is a simple,
specialized language (not a full-blown programming language like PHP).
You meant to prepare the data to display in a real programming
language, like issue database queries and do business calculations,
and then the template displays that already prepared data. In the
template you are focusing on how to present the data, and outside the
template you are focusing on what data to present.

This approach is often referred to as the MVC (Model View Controller)
pattern, and is particularly popular for dynamic Web pages. It helps
in separating the Web page designers (HTML authors) from the
developers (Java programmers usually). Designers won’t face
complicated logic in templates, and can change the appearance of a
page without programmers having to change or recompile code.

While FreeMarker was originally created for generating HTML pages in
MVC web application frameworks, it isn’t bound to servlets or HTML or
anything Web-related. It’s used in non-web application environments as
well.

模板就是把共性(固定不变的)的东西提取出来反复使用,节约时间 提高开发效率。现在主流的模板技术包括:FreeMarker和Velocity,模板技术推崇一种模式:输出=模板+数据。
FreeMarker最开始被MVC Web框架用来生成HTML页面,但它的用途不仅限于HTML或者Web领域,比如本文所要介绍的生成JavaBean源代码。

二 生成JavaBean源代码

本文中将使用Freemarker 生成Person.java类代码,如下:

package com.ricky.java;import java.util.List;/***  @author Ricky Fung*/
public class Person {private Long id;private String name;private Integer age;private List<String> hobby;public void setId(Long id){this.id = id;}public Long getId(){return this.id;}public void setName(String name){this.name = name;}public String getName(){return this.name;}public void setAge(Integer age){this.age = age;}public Integer getAge(){return this.age;}public void setHobby(List<String> hobby){this.hobby = hobby;}public List<String> getHobby(){return this.hobby;}}

2.1 引入Freemarker 依赖

<dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>2.3.23</version></dependency>

2.2 Freemarker 模板文件 person.ftl

package ${packageName};import java.util.List;/***  @author ${author}*/
public class ${className} {<#list attrs as attr> private ${attr.type} ${attr.name};</#list><#list attrs as attr>public void set${attr.name?cap_first}(${attr.type} ${attr.name}){this.${attr.name} = ${attr.name};}public ${attr.type} get${attr.name?cap_first}(){return this.${attr.name};}</#list>
}

2.3 Create a configuration instance

Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);cfg.setDirectoryForTemplateLoading(templateDir);    cfg.setDefaultEncoding("UTF-8");cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);

2.4 Create a data-model
1)In simple cases you can build data-models using java.lang and java.util classes and custom JavaBeans:

  • Use java.lang.String for strings.
  • Use java.lang.Number descents for numbers.
  • Use java.lang.Boolean for boolean values.
  • Use java.util.List or Java arrays for sequences.
  • Use java.util.Map for hashes.
  • Use your custom bean class for hashes where the items correspond to
    the bean properties. For example the price property (getProperty())
    of product can be get as product.price. (The actions of the beans can
    be exposed as well; see much later here)

2)代码构建数据模型

Map<String, Object> root = new HashMap<String, Object>();root.put("packageName", "com.ricky.java");root.put("className", "Person");root.put("author", "Ricky Fung");List<Attribute> attr_list = new ArrayList<Attribute>();attr_list.add(new Attribute("id", "Long"));attr_list.add(new Attribute("name", "String"));attr_list.add(new Attribute("age", "Integer"));attr_list.add(new Attribute("hobby", "List<String>"));root.put("attrs", attr_list);

2.5 获取指定模板

Template temp = cfg.getTemplate("person.ftl");

此时,会在E:/Work/Freemarker/templates目录下查找person.ftl。

2.6 用数据渲染模板

Writer out = new OutputStreamWriter(System.out);
temp.process(root, out);

如果需要将结果序列化到硬盘上,可以使用下面代码:

File dir = new File("E:/Work/Freemarker/src/");if(!dir.exists()){dir.mkdirs();}OutputStream fos = new  FileOutputStream( new File(dir, "Person.java")); //java文件的生成目录   Writer out = new OutputStreamWriter(fos);temp.process(root, out);fos.flush();  fos.close();

最后,贴上CodeGenerator.java完整的代码

package com.ricky.spring.springdemo.freemarker;import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;public class CodeGenerator {public static void main(String[] args) {try {new CodeGenerator().gen();} catch (IOException e) {e.printStackTrace();} catch (TemplateException e) {e.printStackTrace();}}public void gen() throws IOException, TemplateException{Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);cfg.setDirectoryForTemplateLoading(new File("E:/Work/Freemarker/templates"));   cfg.setDefaultEncoding("UTF-8");cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);Template temp = cfg.getTemplate("person.ftl");  // load E:/Work/Freemarker/templates/person.ftl// Create the root hashMap<String, Object> root = new HashMap<String, Object>();root.put("packageName", "com.ricky.java");root.put("className", "Person");root.put("author", "Ricky Fung");List<Attribute> attr_list = new ArrayList<Attribute>();attr_list.add(new Attribute("id", "Long"));attr_list.add(new Attribute("name", "String"));attr_list.add(new Attribute("age", "Integer"));attr_list.add(new Attribute("hobby", "List<String>"));root.put("attrs", attr_list);//      Writer out = new OutputStreamWriter(System.out);
//      Writer out = new OutputStreamWriter(System.out);File dir = new File("E:/Work/Freemarker/src/");if(!dir.exists()){dir.mkdirs();}OutputStream fos = new  FileOutputStream( new File(dir, "Person.java")); //java文件的生成目录   Writer out = new OutputStreamWriter(fos);temp.process(root, out);fos.flush();  fos.close();System.out.println("gen code success!");}
}

利用FreeMarker生成java源代码相关推荐

  1. spring mvc项目中利用freemarker生成自定义标签

    2019独角兽企业重金招聘Python工程师标准>>> spring mvc项目中利用freemarker生成自定义标签 博客分类: java spring mvc +freemar ...

  2. 利用freemarker生成带fusioncharts图片的word简报

    /**  * 利用freemarker生成带fusioncharts图片的word简报  *         烟台海颐软件技术论坛  *         作者  牟云飞 新建 *         毕业 ...

  3. java中利用freemarker生成样式比较复杂的word

    这两天接到一个需求,要在系统中生成word版的需求规格说明书,领导给了个之前的样本给我,要求挺高,必须和给的样本基本一样. 基本样式主要有多级标题.动态图片.页眉页脚等,如下(内容部分因为隐私就不贴出 ...

  4. freemarker 生成 Java 代码

    一.导入maven依赖 <project xmlns=" xmlns:xsi=" xsi:schemaLocation=" <modelVersion> ...

  5. 使用freemarker生成java文件(其他文件也可以)

    参考地址 freemarker 使用模板文件快速创建文件 demo: package com.company;import freemarker.template.Configuration; imp ...

  6. 利用javah生成java本地代码在c语言中的写法

    进入 dos环境下 F:\android0511\ndkCallBack\bin\classes> F:\android0511\ndkCallBack\bin\classes>javah ...

  7. 利用exe4j生成java的exe文件

    使用集成开发工具IDEA生成jar文件 File->Project Structure 2. Artifacts->加号->JAR->From modules with dep ...

  8. Java使用freemarker生成word文件

    首先声明我的项目是一个web项目,生成的word文件直接通过response响应发送给前端.如果不是web项目的话可以像网上的其他教程一样将生成的word保存在本地. 要利用freemarker生成w ...

  9. Java开源工具库使用之java源代码生成库JavaPoet

    文章目录 前言 一.API 1.1 字段 1.2 方法 1.3 代码块 1.4 类 1.5 java 文件 二.使用例子 2.1 数据库表生成 Bean 2.2 Service测试类生成 参考 前言 ...

  10. freemarker生成word文档无法用office打开问题

    错误原因: 利用freemarker生成的word文档利用notepad打开是xml格式.而正常的文档格式利用notepad打开是乱码,需要转换. 代码案例: import com.aspose.wo ...

最新文章

  1. 1675: [Usaco2005 Feb]Rigging the Bovine Election 竞选划区(题解第二弹)
  2. 以编程方式进行NLog的配置【转】
  3. Java 使用ZeroMQ 2.2 进行通信编程
  4. 信息系统项目管理师:第9章:项目人力资源管理-历年真题
  5. EF Core中高效批量删除、更新数据的Zack.EFCore.Batch发布三个新特性
  6. java断言——Assertion
  7. java redis 重连_突破Java面试(23-4) - Redis 复制原理
  8. Recipe terminated with error. vscode latex-workshop新的配置文件
  9. Vuex的State核心概念
  10. Python的argparse
  11. sqlplus connect oracle
  12. hdu 2844 Coins (多重背包+二进制优化)
  13. 计算机windows8黑屏怎么办,Win8电脑开机黑屏只有鼠标光标怎么解决
  14. windows 下关闭135 139 445等危险端口
  15. fftshift详解
  16. PS CC 2014 把一个图层输出为文件的方法
  17. 百度的春晚战事:如何扛住腾讯、阿里都宕机的量?
  18. 2017美团北京java后台开发
  19. Discuz! X2如何禁止帖子发外链和签名链接
  20. 易语言开发免费版的快手去视频水印软件!超简单

热门文章

  1. 写代码常用英文及缩写
  2. Android TelephonyManager获取LET信息及手机基本信息
  3. 数据元数据字典元数据
  4. latex安装血泪史及错误解决
  5. php增加md5加密的方法_php进行md5加密简单实例方法
  6. 在SQL用代码编写好数据库并且保存为sql文件后如何正确的打开?
  7. 基于ssm java jsp的酒店管理系统 前后台
  8. 报表开发神器:phantomjs生成PDF ,Echarts图片,自动生成word文档实战
  9. OOP的核心思想是什么?
  10. Unity3D之创建3D游戏场景