Friday, 26 October 2012

Spring FreeMarker Integration Example (With Annotations)

This post provides a simple example of FreeMarker integration within a Spring application. It is based on the Spring MVC With Annotations example. The code is available on GitHub in the Spring-FreeMarker-Integration directory.

FreeMarker also offers two great tutorials: the Template Author's Guide and the Programmer's Guide.


We need to modify our Web configuration to set a FreeMarker viewer and a FreeMarker configurer:
@ComponentScan(basePackages = "com.jverstry")
public class WebConfig extends WebMvcConfigurerAdapter {

    public ViewResolver getViewResolver() {

        FreeMarkerViewResolver resolver = new FreeMarkerViewResolver();
        // resolver.setPrefix("");

        return resolver;


    public FreeMarkerConfigurer getFreemarkerConfig() {

        FreeMarkerConfigurer result = new FreeMarkerConfigurer();

        return result;


Our controller remains very simple:
public class MyController {

    @RequestMapping(value = "/")
    public String home(Model model) {

        model.addAttribute("MsTime", System.currentTimeMillis());

        return "Home";



FreeMarker Template

We use a simple FreeMarker template:
<!DOCTYPE html>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Spring FreeMarker Example !!!</title>
    This is the Spring FreeMarker Example !!!

    Time is: ${MsTime}!

Maven Dependency

We need the following dependency:

Running The Example

Once compiled, the example can be run with mvn tomcat:run. Then, browse:


The home page will display:

More Spring related posts here.