I would like to know how Velocity Template works without initializaion.

There is no Initialization : like below

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

Code which runs without 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());

Output :

Hello World from Java Source
Hello World from Velocity Template
有帮助吗?

解决方案

the getTemplate method performs an initialization check and does the init if Velocity is not yet initialized.

From Velocity 1.7 Source:

 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);
            }
        }
    }
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top