一 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