Spring & Velocity
Published by peter January 17th, 2006 in java.Brainstorming a bit on creating e-mail templates I remembered I had seen people use Velocity to do this. Together with Spring it seemed ideal for the job!
So, to see how Spring and Velocity fit together I mocked up a some test:
first, setup the application context:
“http://www.springframework.org/dtd/spring-beans.dtd”>
Then, create a simple unit test (well, technically, provide the meanse to execute) to run:
package com.finalist.velo;
import java.util.HashMap;
import java.util.Map;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.VelocityException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.ui.velocity.VelocityEngineUtils;
import junit.framework.TestCase;
public class VelocityTest extends TestCase {
private ApplicationContext ctx = null;
private VelocityEngine ve = null;
protected void setUp() throws Exception {
String[] paths = { “applicationContext.xml” };
ctx = new ClassPathXmlApplicationContext(paths);
ve = (VelocityEngine) ctx.getBean(”velocityEngine”);
}
public void testSimpleTemplate(){
try {
Map properties = new HashMap();
properties.put(”name”,”peter”);
properties.put(”array”,new String[]{”one”,”two”,”three”});
properties.put(”testBean”,new TestBean(”property a”,new Integer(123))); // simple bean with 2 properties
String result = VelocityEngineUtils.mergeTemplateIntoString(ve,”simple.vm”,properties);
System.out.println(result);
}
catch (VelocityException e) {
e.printStackTrace();
}
}
}
Create a simple template, and put in ${classpath}/velocity as defined by the ‘resourceLoaderPath’ property in the applicationContext config:
My name is $name
#foreach( $item in $array )
* $item
#end
alle items, behalve element “two”
#foreach( $item in $array )
#if( $item != “two”)
* $item
#end
#end
bean property (String) $testBean.a from $testBean.class.name
bean property (Integer) $testBean.b from $testBean.class.name
And: instant gratification:
My name is peter
* one
* two
* three
alle items, behalve element “two”
* one
* three
bean property (String) property a from com.finalist.velo.TestBean
bean property (Integer) 123 from com.finalist.velo.TestBean
Seems really fit for the email templating I had in mind!




















0 Responses to “Spring & Velocity”
Please Wait
Leave a Reply