如何使用 Apache Velocity 生成代码

开始使用 Velocity,这是一个开源的、基于 Java 的模板引擎和代码生成器,可以将模板转换为源代码。
119 位读者喜欢这篇文章。
Binary code on a computer screen

公共领域,通过 LibreShot

Apache Velocity 是一个开源的、基于 Java 的模板引擎和代码生成器,可以将模板转换为源代码。因为它是在 Java 中实现的,所以它能够解释各种模板并为任何语言(Web、服务、SQL、脚本等)生成代码,尽管它似乎主要面向 Web 开发。

Velocity 的结构

Velocity 的结构由引擎和工具组成。其核心是 Velocity 引擎,它使用定义的模板,解释模板语言,并生成代码。

模板使用 Velocity 模板语言 (VTL) 定义,这是一种带有有效指令的简单语言。VTL 语句是指令或变量,变量可以是独立的或类方法。

VTL 表达式的示例包括:

package ${packagename};
在 Java 中插入包声明,其中包名称定义为 packagename
public ${classname} implements Serializable {
添加一个名为 classname 的类
#foreach( $property in $properties )
 public ${property.fieldType} get${property.getField()}() {
     return this.${property.fieldName};
 }
#end
为所有已定义的属性创建 getter 方法

Velocity 工具是基本用户友好功能的集合。有 GenericTools,这是一组类,为在标准 Java SE Velocity 项目中使用工具提供基本基础设施,以及一组用于通用 Velocity 模板的工具。它们包括 DateTool、MathTool、NumberTool、SortTool 和 XmlTool。还有 VelocityView 工具,其中包括“所有 GenericTools,并为在 Web 应用程序(Java EE 项目)的视图层中使用 Velocity 添加基础设施和专用工具”。VelocityView 工具包括 BrowserTool、CookieTool 和 ImportTool

Velocity 的优点和缺点

Velocity 易于使用,并且能够生成任何语言。缺点是,理解和应用其模板语言需要一个学习曲线。Velocity 是无词法和本体论的。它不了解其生成的模块的设计能力。作为一个实际示例,Velocity 可以使用控制器的模板(例如,模型-视图-控制器或架构风格)并生成代码,但它不了解控制器的概念。这既是优点也是缺点,生成器简单易用,但不了解设计的适用性。

使用 Velocity

Velocity 的 Java 库可在 Maven 仓库中找到。要使用 .jar 文件,请在您的 Maven 构建配置中定义 Velocity 的最新版本。(截至本文撰写时,Velocity 1.7 是最新版本。)例如,在您的 Maven 项目对象模型 (POM) 中输入以下内容:

<dependency>
	<groupId>org.apache.velocity</groupId>
	<artifactId>velocity</artifactId>
	<version>1.7</version>
</dependency>

Java Hello World 示例

要生成代码,您需要两件事:

  1. 用于生成的 Velocity 模板,例如 java_example.vm
    public class ${className} {
    
        public static void main(String[] args) {
            System.out.println("${message}");
        }
    
    }
  1. 使用模板生成代码的 Velocity 生成器,例如 VelocityStartGenerator.java
    public class VelocityStartGenerator {
     
        static String inputTemplate = "java_example.vm";
        static String className = "VelocityExample";
        static String message = "Hello World!";
        static String outputFile = className + ".java";
    	
        public static void main(String[] args) throws IOException {
        	
            VelocityEngine velocityEngine = new VelocityEngine();
            velocityEngine.init();
          
            VelocityContext context = new VelocityContext();
            context.put("className", className);
            context.put("message", message);
    
            Writer writer = new FileWriter(new File(outputFile));
            Velocity.mergeTemplate(inputTemplate, "UTF-8", context, writer);
            writer.flush();
            writer.close();
            
            System.out.println("Generated " + outputFile);
        }
    }

构建并运行 Velocity 生成器。使用 Maven:

$ mvn clean install
$ mvn exec:java -Dexec.mainClass=velocity_generator.VelocityStartGenerator

这将生成文件 VelocityExample.java,如下所示:

public class VelocityExample {

    public static void main(String[] args) {
        System.out.println("Hello World!");
    }

}

构建并运行它,它将显示:“Hello World!”

$ javac VelocityExample.java
$ java VelocityExample
Hello World!

试用一下生成器。您能让生成的文件显示“Howdy”吗?

接下来,查看以下 HTML 和 shell 脚本生成示例。

HTML Hello World 示例

Velocity 模板

(html_example.vm)
<!DOCTYPE html>
<html>
<body>

<h1>$message</h1>

</body>
</html>
Velocity 生成器

(VelocityStartGenerator.java)
public class VelocityStartGenerator {
 
    static String inputTemplate = "http_example.vm";
    static String message = "Hello World!";
    static String outputFile = "helloworld.html";
	
    public static void main(String[] args) throws IOException {
    	
        VelocityEngine velocityEngine = new VelocityEngine();
        velocityEngine.init();
      
        VelocityContext context = new VelocityContext();
        context.put("message", message);

        Writer writer = new FileWriter(new File(outputFile));
        Velocity.mergeTemplate(inputTemplate
        		, "UTF-8", context, writer);
        writer.flush();
        writer.close();
        
        System.out.println("Generated " + outputFile);
    }
}
生成的文件

(helloworld.html)
<!DOCTYPE html>
<html>
<body>

<h1>Hello World!</h1>

</body>
</html>
生成的输出
Velocity HTML output

Shell 脚本 Hello World 示例

Velocity 模板

(sh_example.vm)
echo $message
Velocity 生成器

(VelocityStartGenerator.java)
public class VelocityStartGenerator {
 
    static String inputTemplate = "sh_example.vm";
    static String message = "Hello World!";
    static String outputFile = "helloworld.sh";
	
    public static void main(String[] args) throws IOException {
    	
        VelocityEngine velocityEngine = new VelocityEngine();
        velocityEngine.init();
      
        VelocityContext context = new VelocityContext();
        context.put("message", message);

        Writer writer = new FileWriter(new File(outputFile));
        Velocity.mergeTemplate(inputTemplate, "UTF-8", context, writer);
        writer.flush();
        writer.close();
        
        System.out.println("Generated " + outputFile);
    }
}
生成的文件

(helloworld.sh)
echo Hello World!
生成的输出
Velocity shell output

结论

您可以在 Apache 的 GitHub 仓库中找到 Velocity,并且您可以在 GitLabGitHub 上找到其使用示例。

这是对 Apache Velocity 的简要快速介绍。您使用过它吗?您怎么看?请在评论中分享您的想法。

接下来阅读什么
标签
User profile image.
Girish 在印度一家全球 IT 服务组织拥有超过 20 年的技术和软件经验。Girish 是“I Got”云平台的架构师,该平台旨在提升金字塔底层,采用开源堆栈和现代架构模式(如微服务、容器化和多租户)构建。Girish 撰写关于开源和技术主题的文章。

评论已关闭。

© . All rights reserved.