在Velocity1.2版本以后,开发者现在又两种选择来使用Velocity引擎,单例模型(singleton model)和单独实例模型(separate instance model)。这是相同的核心代码的2种使用方式,他们都提供了简单地将Velocity集成到你的Java应用中。
单一实例模式(Singleton Model)
这是一个传统模式,Velocity引擎在JVM中(或者是一个Web应用)只有一个共享实例,它可以非常方便的允许局部配置并且共享资源。举一个例子,在使用Servlet 2.2+兼容的Web应用中,每个Web应用程序都可以有自己的运行实例,这就是一个非常合适的模型。
1 import org.apache.velocity.app.Velocity;
2 import org.apache.velocity.Template;
3
4 ...
5
6 /*
7 * Configure the engine - as an example, we are using
8 * ourselves as the logger - see logging examples
9 */
10
11 Velocity.setProperty(
12 Velocity.RUNTIME_LOG_LOGSYSTEM, this);
13
14 /*
15 * now initialize the engine
16 */
17
18 Velocity.init();
19
20 ...
21
22 Template t = Velocity.getTemplate("foo.vm");
单独实例模型(Separate Instance)
1.2版本新出来的,单独实例模式允许你创建、配置并且在JVM(或者Web应用)上,Velocity实例的数量你想要多少就可以使用多少。当你希望支持分散的配置的时候这个是非常有用的,比如在同一个应用的模版路径,日志等等。为了使用单独实例,将使用org.apache.velocity.app.VelocityEngine类。举个例子,和上面的单例例子对应:
1 import org.apache.velocity.app.VelocityEngine;
2 import org.apache.velocity.Template;
3
4 ...
5
6 /*
7 * create a new instance of the engine
8 */
9
10 VelocityEngine ve = new VelocityEngine();
11
12 /*
13 * configure the engine. In this case, we are using
14 * ourselves as a logger (see logging examples..)
15 */
16
17 ve.setProperty(
18 VelocityEngine.RUNTIME_LOG_LOGSYSTEM, this);
19
20 /*
21 * initialize the engine
22 */
23
24 ve.init();
25
26 ...
27
28 Template t = ve.getTemplate("foo.vm");
就像你看到的,这个是非常简单明了的。在使用Velocity单一实例还是单独实例的需求上,除了一些简单语法上的变化,在应用和模版中没有其他高级别数据结构的变化。
作为一个程序员,如果使用单一实例的话,使用Velocity的内部类org.apache.velocity.app.Velocity,如果你使用非单一实例模型的话则使用org.apache.velocity.app.VelocityEngine。
在任何时候需要应用使用org.apache.velocity.runtime包内部的Runtime,RuntimeConstants,RuntimeSingleton或者RuntimeInstance类,因为这些是供内部使用,所以可能会随时间而改变。就像上面提到的,这些位于org.apache.velocity.runtime包里的类,也是Velocity和VelocityEngine的类。如果当需要这些类的时候无法找到,不要犹豫提议变化 - 这些类都是为应用开发者提供的。
转载于:https://my.oschina.net/secyaher/blog/274480