利用FreeMarker生成java源代码

Apache FreeMarker是一个模板引擎,常用于MVC模式中分离网页设计与开发。本文介绍了如何利用FreeMarker生成JavaBean源代码,包括引入依赖、创建模板文件、配置实例、构建数据模型、获取模板和渲染数据,最终生成Person.java类代码。
摘要由CSDN通过智能技术生成

一 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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值