没有init()的Velocity Engine

时间:2014-04-05 08:30:31

标签: java velocity

我想知道Velocity Template如何在没有初始化的情况下工作。

没有初始化:如下所示

     Velocity.init();            
         OR
     VelocityEngine velocity = new VelocityEngine();
     velocity.init();

不使用init()运行的代码:

System.out.println("Hello World from Java Source");     
VelocityContext context = new VelocityContext();
context.put( "name", new String("Velocity") );

Template template = Velocity.getTemplate("default-template.vm");        
StringWriter sw = new StringWriter();
template.merge( context, sw );
System.out.println(sw.toString());

输出

Hello World from Java Source
Hello World from Velocity Template

1 个答案:

答案 0 :(得分:2)

getTemplate方法执行初始化检查,如果尚未初始化Velocity,则执行init。

来自Velocity 1.7来源:

 public Template getTemplate(String name, String  encoding)
            throws ResourceNotFoundException, ParseErrorException
        {
            requireInitialization();

            return (Template)
                    resourceManager.getResource(name,
                        ResourceManager.RESOURCE_TEMPLATE, encoding);
        }



 private void requireInitialization()
    {
        if (!initialized)
        {
            try
            {
                init();
            }
            catch (Exception e)
            {
                getLog().error("Could not auto-initialize Velocity", e);
                throw new RuntimeException("Velocity could not be initialized!", e);
            }
        }
    }